You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Vue-Konva动态创建的Rect/形状添加Text/Label以实现单独标识

Vue-Konva动态Rect添加内部文本与专属标识实现方案

1. 为Rect添加内部Text/Label

Konva 中单个 Shape 无法直接嵌套子元素,因此我们可以将 Rect 和对应的 Text 放入同一个 Konva.Group 组件中统一管理坐标,实现文本内嵌在形状内部的效果:

核心代码示例

<template>
  <v-stage ref="stage" :config="stageConfig">
    <v-layer>
      <!-- 每个Group对应一个Rect+Text组合,统一设置坐标 -->
      <v-group 
        v-for="shape in shapeList" 
        :key="shape.id"
        :x="shape.x"
        :y="shape.y"
      >
        <v-rect
          :config="{
            width: shape.width,
            height: shape.height,
            fill: shape.fillColor,
            stroke: '#333',
            // 专属名称/ID配置
            name: shape.uniqueName,
            id: shape.id
          }"
        />
        <!-- 内部文本,相对Rect居中显示 -->
        <v-text
          :config="{
            text: shape.labelContent,
            fontSize: 14,
            fill: '#fff',
            // 相对Rect居中定位配置
            x: shape.width / 2,
            y: shape.height / 2,
            offsetX: shape.width / 2,
            offsetY: shape.height / 2,
            align: 'center'
          }"
        />
      </v-group>
    </v-layer>
  </v-stage>
</template>

如果需要带背景、边框等更复杂的标签样式,可直接使用 v-label 组件替代上述的Rect+Text组合,通过text和tag属性快速配置标签样式。

2. 为Shape设置专属名称实现单独区分

有两种常用的标识配置方式,可按需选择:

  • name标识:适用于同类形状的批量管理,在config中传入name字段后,可通过类选择器语法查找对应形状
  • id标识:适用于单个形状的唯一匹配,性能更高,通过id选择器语法即可直接定位

形状查找代码示例

// 查找所有name为"custom-rect"的形状
const rectList = this.$refs.stage.getStage().find('.custom-rect')
// 查找id为"rect-001"的单个形状
const targetRect = this.$refs.stage.getStage().findOne('#rect-001')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 03:06:00