如何在 Vue 中缓存画布形状?
如果你想在 Vue 应用中缓存一个节点,你需要访问 Konva 节点并使用 node.cache()
函数。
要访问节点,你可以使用引用和 component.getNode()
方法:
// 在模板中:
<v-group ref="group">
// 在代码中稍后:
this.$refs.group.getNode().cache();
说明:尝试拖动整个舞台。然后启用缓存并再次尝试。你应该会看到启用缓存后性能大幅提升。
<template> <div> <v-stage ref="stage" :config="stageConfig"> <v-layer ref="layer"> <v-group ref="group"> <v-star v-for="item in list" :key="item.id" :config="{ x: item.x, y: item.y, rotation: item.rotation, id: item.id, numPoints: 5, innerRadius: 30, outerRadius: 50, fill: '#89b717', opacity: 0.8, shadowColor: 'black', shadowBlur: 10, shadowOpacity: 0.6, scaleX: item.scale, scaleY: item.scale, }" /> </v-group> </v-layer> </v-stage> <div class="cache"> <input type="checkbox" @change="handleCacheChange"> 缓存形状 </div> </div> </template> <script> const width = window.innerWidth; const height = window.innerHeight; export default { data() { return { list: [], dragItemId: null, stageConfig: { width: width, height: height, draggable: true } }; }, methods: { handleCacheChange(e) { const shouldCache = e.target.checked; if (shouldCache) { this.$refs.group.getNode().cache(); } else { this.$refs.group.getNode().clearCache(); } } }, mounted() { // 生成 300 个随机星形 for (let n = 0; n < 1000; n++) { this.list.push({ id: Math.round(Math.random() * 10000).toString(), x: Math.random() * width, y: Math.random() * height, rotation: Math.random() * 180, scale: Math.random() }); } } }; </script> <style> .cache { position: absolute; top: 0; left: 0; } </style>