You need to enable JavaScript to run this app. Vue Konva如何动态创建N+1个stage 单个stage创建方法参考
优惠活动
大模型
产品
解决方案
定价
更多

Vue Konva如何动态创建N+1个stage 单个stage创建方法参考

如何创建N+1个Konva Stage

通过v-for循环渲染<v-stage>即可实现批量创建,具体实现方式如下:

步骤1:准备多Stage配置数组

首先在组件的响应式数据中定义存储所有stage配置的数组,每个元素包含对应stage的独立配置、内部图层元素的数据源,示例代码(Vue3):

import { ref } from 'vue'

// 定义Stage基数N,最终生成N+1个Stage
const N = 3 
const stageList = ref([])
const stageRefs = ref([]) // 存储所有Stage实例,方便后续调用API

// 初始化N+1个Stage的独立配置
for (let i = 0; i <= N; i++) {
  stageList.value.push({
    id: `stage_${i}`,
    // 每个Stage独立的Konva配置,避免引用共用对象互相影响
    config: {
      width: 400,
      height: 200,
    },
    // 当前Stage内部的圆形元素专属数据
    circleItems: [
      { radius: 40, x: 50 + i*30, y: 50, fill: 'red' },
      { radius: 30, x: 150 + i*30, y: 80, fill: 'blue' }
    ]
  })
}

步骤2:模板循环渲染Stage

直接用v-for遍历配置数组生成多个<v-stage>即可,模板代码:

<template>
  <v-stage
    v-for="(stageItem, idx) in stageList"
    :key="stageItem.id"
    :config="stageItem.config"
    :ref="el => { if (el) stageRefs[idx] = el }"
  >
    <v-layer>
      <v-circle
        v-for="(circle, i) in stageItem.circleItems"
        :config="circle"
        :key="`circle_${idx}_${i}`"
        :ref="`circle_${idx}_${i}`"
      />
    </v-layer>
  </v-stage>
</template>

注意事项

  • 每个Stage的配置对象要单独声明,不要复用同一个引用对象,避免修改一个Stage的配置时影响其他Stage
  • 如果后续有动态增删Stage的需求,不要用数组索引作为key值,需提前给每个Stage配置生成唯一id作为key
  • 可通过索引区分不同Stage的ref实例,方便后续调用Konva原生API操作对应Stage

内容的提问来源于stack exchange,提问作者scranley

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 00:45:02