java dom解析svg_javascript – 如何操作SVG DOM并创建元素?

如何获取SVG DOM根目录,并以编程方式开始向其添加子项,而不是通过标记添加SVG元素?

解决方法:

var svg = document.documentElement;

var svgNS = svg.namespaceURI;

var circle = document.createElementNS(svgNS,'circle');

circle.setAttribute('cx',100);

circle.setAttribute('cy',200);

circle.setAttribute('r',50);

circle.setAttribute('fill','red');

circle.setAttribute('stroke','black');

circle.setAttribute('stroke-width','20px');

circle.setAttribute('stroke-opacity','0.5');

svg.appendChild(circle);

因为发出所有这些setAttribute调用会非常麻烦,所以我经常使用这样的函数:

// Create an SVG element on another node with a set of attributes.

// Attributes with colons in the name (e.g. 'xlink:href') will automatically

// find the appropriate namespace URI from the SVG element.

// Optionally specify text to create as a child node, for example

// createOn(someGroup,'text',{x:100,'text-anchor':'middle'},"Hello World!");

function createOn(root,name,attrs,text){

var doc = root.ownerDocument, svg = root;

while (svg.tagName!='svg') svg = svg.parentNode;

var el = doc.createElementNS(svg.namespaceURI,name);

for (var a in attrs){

if (!attrs.hasOwnProperty(a)) continue;

var p = a.split(':');

if (p[1]) el.setAttributeNS(svg.getAttribute('xmlns:'+p[0]),p[1],attrs[a]);

else el.setAttribute(a,attrs[a]);

}

if (text) el.appendChild(doc.createTextNode(text));

return root.appendChild(el);

}

在行动中,上述文件变得更加简单:

var svg = document.documentElement;

createOn(svg,'circle',{

cx:100, cy:200, r:50,

fill:'red', stroke:'black',

'stroke-width':'20px', 'stroke-opacity':0.5

});

// …function from above…

标签:javascript,dom,svg

来源: https://codeday.me/bug/20190610/1209062.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值