繁体   English   中英

从外部SVG复制某些元素组,然后使用该组创建另一个SVG

[英]Clone certain group of elements from external SVG and use that group to create another SVG

我正在尝试仅使用外部SVG文件(icons.svg)中的某些元素组,并使用选定的组来创建另一个SVG标签。 尝试采用这种方式的原因是,我不想为每个图标都使用单独的SVG文件,因为最终会有大量的SVG文件。

我更喜欢使用D3,目前我的HTML代码正在执行(这不起作用):

 <!DOCTYPE html> <meta charset="utf-8"> <head><script src="https://d3js.org/d3.v3.js"></script></head> <body> <script> d3.xml("icons.svg").mimeType("image/svg+xml").get(function(error, xml) { if (error) throw error; iconSvg = xml.getElementsByTagName("svg")[0]; sel = d3.select(iconSvg).selectAll("#icon2"); var newSvg = d3.select("body").append("svg") .attr({"id":"newicon", "width":50, "height":50 }).append(sel); }); </script> 

以下是“ icons.svg”文件的内容:

 <?xml version="1.0" encoding="utf-8"?> <svg width="100%" version="1.1" id="icons" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 50 50" style="enable-background:new 0 0 50 50;" xml:space="preserve"> <g id="icon1" width="16" height="16" > <circle cx="7.5" cy="7.5" r="6.0" stroke="black" stroke-width="1" fill="#00AD5A" /> </g> <g id="icon2" width="16" height="16" > <circle cx="7.5" cy="7.5" r="6.0" stroke="black" stroke-width="1" fill="#FF0000" /> </g> <g id="icon3" width="16" height="16" > <circle cx="7.5" cy="7.5" r="6.0" stroke="black" stroke-width="1" fill="#FF00FF" /> </g> </svg> 

感谢您的帮助!

我找到了解决该问题的方法。 我换了线

sel = d3.select(iconSvg).selectAll("#icon2");

对此:

sel = d3.select(iconSvg).select("#icon2").html();

var newSvg = d3.select("body").append("svg")  
        .attr({"id":"newicon", "width":50, "height":50
        }).append(sel);

对此:

var newSvg = d3.select("body").append("svg")  
        .attr({"id":"newicon", "width":50, "height":50
        }).append("g").html(sel);

最终结果就是我想要的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM