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

如何在React Konva的矩形内部添加文本?

解决React Konva矩形内添加问号的问题

你的代码存在两个核心问题导致问号无法正常显示:

  1. React Konva的<Rect>组件不支持嵌套子元素,不能将<Text>放在<Rect>标签内部;
  2. 文本的定位、对齐参数不完整,加上Group与Rect的坐标叠加,导致文本位置偏移或不可见。

修正后的代码

<Grid item xs={12} lg={3} style={{border:'5px solid white'}}>
  <Stage width={1200} height={1200}>
    <Layer>
      <RegularPolygon
        sides={3}
        x={50}
        y={100}
        width={100}
        height={100}
        stroke="orange"
      />

      <RegularPolygon
        sides={3}
        x={200}
        y={100}
        width={100}
        height={100}
        stroke="#00FFFF"
      />

      <Rect
        x={300}
        y={50}
        width={80}
        height={80}
        stroke="orange"
      />

      {/* 用Group统一管理矩形和文本的位置 */}
      <Group x={450} y={30}>
        <Rect
          x={0}  {/* 改为相对Group的坐标,避免双重偏移 */}
          y={0}
          width={100}
          height={100}
          stroke="white"
          strokeWidth={5}
        />
        {/* 文本与矩形同级,放在Group内 */}
        <Text
          fontSize={40}  {/* 调大字号提升可见度 */}
          text="?"
          fill="white"  {/* 用fill替代stroke,让问号实体显示 */}
          x={0}
          y={0}
          width={100}  {/* 匹配矩形宽度,配合align实现水平居中 */}
          height={100} {/* 匹配矩形高度,配合verticalAlign实现垂直居中 */}
          align="center"
          verticalAlign="middle"
        />
      </Group>
    </Layer>
  </Stage>
</Grid>

关键修改说明

  • 移除Rect的子元素嵌套:将<Text>从<Rect>中取出,与Rect放在同一个<Group>下,Konva通过Group管理关联图形的位置关系;
  • 调整坐标体系:Group已设置全局偏移x={450} y={30},内部的Rect和Text改用相对Group的坐标(x=0 y=0),避免双重偏移;
  • 完善文本对齐参数:给Text设置与矩形一致的width和height,配合align="center"和verticalAlign="middle"实现完全居中;
  • 优化文本样式:将stroke改为fill,避免问号仅显示白色边框,同时调大字号增强可见性;
  • 修正Grid边框样式:原代码border:'5px 5px 5px 5px solid white'写法错误,改为标准的border:'5px solid white'。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 21:25:17