【问题标题】:Filling an existing svg rectangle with text用文本填充现有的 svg 矩形
【发布时间】:2018-08-25 13:44:40
【问题描述】:

我正在尝试使用 JavaScript 创建一个包含文本的 SVG 矩形。我已经得到了矩形(由 morris.js,一个图表库生成),但似乎无法输入文本。

我想要实现的输出看起来有点像这样:

<svg>
  <g>
    <rect x="0" y="0" width="100" height="100" fill="red"></rect>
    <text x="0" y="50" font-family="Verdana" font-size="35" fill="blue">Hello</text>
  </g>
</svg>

这是我现在的代码(sn-p 不会运行,因为 rectangleElement 在这里未定义):

console.log(rectangleElement);
/* output:
<rect x="1205.5019308035712" y="0" width="193.5206919642857" height="307" r="0" rx="0" ry="0" fill="#E5E5E5" stroke="none" fill-opacity="0.8" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); fill-opacity: 0;"></rect>
*/

var t = document.createElementNS('http://www.w3.org/2000/svg', 'text');
var g = document.createElementNS('http://www.w3.org/2000/svg', 'g');

g.appendChild(t);
g.appendChild(rectangleElement);

console.log(g);
/* output:
<g><text></text></g>
*/

如您所见,rectangleElement 未添加到我的组 (g)。尝试将矩形附加到组时,我也没有在控制台中收到任何错误。

关于我可能做错的任何想法?

【问题讨论】:

    标签: javascript svg raphael morris.js


    【解决方案1】:

    我最终自己修复了它。我完全不确定问题出在哪里,当我在下面添加看似无关的代码时,它开始工作了。

    var txtElem = document.createElementNS("http://www.w3.org/2000/svg", "text");
    txtElem.setAttributeNS(null,"x",20);
    txtElem.setAttributeNS(null,"y",40);
    var theText = "text";
    var theMSG = document.createTextNode(theText);
    txtElem.appendChild(theMSG);
    

    【讨论】:

      猜你喜欢
      • 2019-10-11
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 2016-02-24
      • 2014-12-26
      • 1970-01-01
      • 2011-10-07
      相关资源
      最近更新 更多