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

JS动态生成SVG树图时text文本不显示问题咨询

问题原因

动态生成SVG内元素时,所有SVG子元素都必须在SVG命名空间下创建才会被浏览器正确识别渲染。
你的代码中创建<g>、<rect>元素时都正确使用了带SVG命名空间参数的document.createElementNS()方法,但创建<text>文本元素时错误使用了普通HTML元素的创建方法document.createElement("text"):

  • 该方法创建的text元素属于HTML默认命名空间,不会被当作SVG文本节点渲染,因此动态运行时文本不显示
  • 当你把动态生成的SVG代码复制为静态HTML粘贴到页面中时,浏览器解析静态SVG内部的标签会自动将其归入SVG命名空间,因此静态打开时文本可以正常显示
修复方案

将创建text元素的代码替换为带SVG命名空间的创建方法即可,修改对应代码行:

// 原错误代码
// let text = document.createElement("text");
// 修复后代码
let text = document.createElementNS("http://www.w3.org/2000/svg", "text");
修复后完整代码参考
<html>
  <head>
    <style>
    #something{
      width: 750px;
    }
    </style>
  </head>
  <body>
    <div id="something">
      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 900 600" preserveAspectRatio="xMinYMin meet">
      </svg>
    </div>
    <script type="text/javascript" src="https://unpkg.com/treemap-squarify@1.0.1/lib/bundle.min.js"></script>
    <script>
        const result = Treemap.getTreemap({
          data: [
            { value: 18, color: 'red' },
            { value: 7, color: 'pink' },
            { value: 4, color: 'blue' },
            { value: 1, color: 'orange' },
            { value: 5, color: 'green' },
            { value: 9, color: 'grey' },
           ],
          width: 900,
          height: 600,
        });

        const svg = document.querySelector("svg");
        for(let i = 0; i < result.length; i++){
          let newG = document.createElementNS("http://www.w3.org/2000/svg", "g");

          let rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
          rect.setAttribute("x", result[i].x);
          rect.setAttribute("y", result[i].y);
          rect.setAttribute("width", result[i].width);
          rect.setAttribute("height", result[i].height);
          rect.setAttribute("fill", result[i].data.color);

          // 使用正确的SVG命名空间创建text元素
          let text = document.createElementNS("http://www.w3.org/2000/svg", "text");
          text.setAttribute("x", result[i].x+(result[i].width/2));
          text.setAttribute("y", result[i].y+(result[i].height/2));
          text.setAttribute("fill", "white");
          text.setAttribute("font-family", "Verdana");
          text.setAttribute("font-size", "12");
          // 可选:增加居中属性让文本在矩形内真正居中
          text.setAttribute("text-anchor", "middle");
          text.setAttribute("dominant-baseline", "middle");

          let textNode = document.createTextNode(result[i].data.value);
          text.appendChild(textNode);

          newG.appendChild(rect);
          newG.appendChild(text);
          svg.appendChild(newG);
        }
    </script>
  </body>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 20:30:51