如何将svg代码转换为javascript代码

How to translate svg code to javascript code?

本文关键字:代码 转换 javascript svg      更新时间:2023-09-26

我在这里了解到stackoverflow,您可以如下动态地将svg元素插入HTML文件中。

  var svgnode = document.createElementNS('http://www.w3.org/2000/svg','svg'); 
  var path = document.createElementNS('http://www.w3.org/2000/svg','path');
  path .setAttribute("d","......");
  svgnode.appendChild(path);
  document...........appendChild(svgnode);

而且效果很好。我希望你也能继续这样做。

var defs = document.createElementNS('http://www.w3.org/2000/svg','defs');
var use = document.createElementNS('http://www.w3.org/2000/svg','use');
var path2=document.createElementNS('http://www.w3.org/2000/svg','path');
path2.setAttribute("d","....");
path2.setAttribute("id","path2");
defs.appendChild(path2);
use.setAttribute("xlink:href","#path2");
use.setAttribute("x","10");
use.setAttribute("y","10");
svgnode.appendChild(defs);
svgnode.appendChild(use);
document...........appendChild(svgnode);

但第二次失败了。

请指出第二个错误的地方。

提前谢谢。

问题只是xlink:href,它需要在xlink命名空间中:

use.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#path2");

其余的代码将在无名称空间的形式中正常工作。