javascript - 通过 javascript 的 SVG 文本路径不绘图

标签 javascript svg

我想生成一个简单的textPath。我原以为这会花费我 5 分钟的时间,但现在已经过去了几个小时,我已经通过 stack Overflow 和 google 进行了搜索,发现我的实现看起来是正确的。我不确定缺少什么。我可以将 TextNode 附加到文本容器,但一旦我将 textPath 放在上面,就不会在 SVG 元素中呈现。

<!DOCTYPE html="">
<html>  
<meta name="description" content="">
<head>
<script language="Javascript">


function drawTextPath(evt){

var mypath2 = document.createElementNS("http://www.w3.org/2000/svg","path"); 

mypath2.setAttributeNS(null, "id", "#path");    
mypath2.setAttributeNS(null, "d","M400 50 l200 0");
mypath2.setAttributeNS(null,"fill", "none");
mypath2.setAttributeNS(null,"stroke","red");
document.getElementById("bodySVG").appendChild(mypath2);





var text1 = document.createElementNS("http://www.w3.org/2000/svg", "text");
text1.setAttributeNS(null, "fill", "blue");
text1.setAttributeNS(null,"font-size","30px");
text1.setAttributeNS(null,"x", "0");
text1.setAttributeNS(null,"y", "70");


var textpath = document.createElementNS("http://www.w3.org/2000/svg","textPath");
  textpath.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#path");   
  var ringdatenode = document.createTextNode("This is the text");
  textpath.appendChild(ringdatenode);
  text1.appendChild(textpath);
  document.getElementById("bodySVG").appendChild(text1);

}

</script>
</head>

<body>

<p>Welcome </p>

<svg id="bodySVG" height="800" width="1500" xmlns="http://www.w3.org/2000/svg" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:xlink="http://www.w3.org/1999/xlink">



<circle id="todayring" cx="100" cy="20" r="18" stroke="black" stroke-width="5"    fill="orange" onclick="drawTextPath(evt);"></circle>

</svg>
</body>
</html>

最佳答案

你已经很接近了。 id 应该是路径而不是#path。

mypath2.setAttributeNS(null, "id", "path");

您将其称为#path,就像您所做的那样。

关于javascript - 通过 javascript 的 SVG 文本路径不绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25233629/

相关文章:

javascript - 在html网站中移动圆圈

javascript - 如何通过下拉框过滤 div 的内容并隐藏结果,直到选择该选项。 (包括jsfiddle)

javascript - Canvas 与 DOM 在 JavaScript 游戏开发中的优缺点是什么?

asp.net - 是否有任何工具可以将旧版 VML 转换为 SVG?

在 Internet Explorer 9 中使用 SVG 背景图像进行 CSS 2D 转换

javascript - 如何使用 webdriverjs 控制新窗口?

javascript - 如何给图像一个最大高度但保持纵横比?

css - 如何更改使用 webpack 打包的内联 svg 的颜色?

css - 如何放大svg?

html - SVG 不显示在 Safari 的 img 标签中