简体   繁体   English

如何遍历SVG中的所有元素而不丢失结构

[英]How to iterate through all elements in an SVG without losing structure

I built a tool that loads user generated SVG's to edit. 我构建了一个加载用户生成的SVG进行编辑的工具。 But since it's user generated content, I'd like to loop through all elements in the SVG (loaded using the load() function of Snap) before appending it to the editor to set fill colors and remove unwanted elements. 但是,由于它是用户生成的内容,因此我想遍历SVG中的所有元素(使用Snap的load()函数加载),然后再将其添加到编辑器中以设置填充颜色并删除不需要的元素。

The code I now have works fine as for the normalizing part, but it flattens the whole SVG hierarchy: 我现在拥有的代码对于规范化部分工作正常,但它使整个SVG层次结构变得平坦:

var allNodes = source.selectAll('*:not(svg):not(defs):not(desc):not(title)');
allNodes.forEach(function(subelement) {
    // loop through all elements
    logocreator.normalizeSvgElement(subelement, viewBox);
});
return allNodes;

Some of the SVG's rely on the hierarchy in the SVG file. 某些SVG依赖于SVG文件中的层次结构。 For example, one SVG contained multiple icons (paths) in groups and all of them, except one, had a style="display: none" . 例如,一个SVG分组包含多个图标(路径),除一个以外,所有其他图标均具有style="display: none" When flattening the elements in the SVG all paths were shown and a big mess was the result. 当展平SVG中的元素时,会显示所有路径,结果是一团糟。

So, what I need is a way to loop through all elements in the source of a SVG and normalize each individual element, before adding the contents to my own SVG (the editor). 因此,我需要的是一种在将内容添加到我自己的SVG(编辑器)之前,遍历SVG源代码中所有元素并对每个元素进行规范化的方法。

I found the problem.. in the example above I create an array of all elements and after looping through this array I return the array to the icon loading method. 我发现了问题..在上面的示例中,我创建了一个所有元素的数组,并在遍历该数组后将数组返回到图标加载方法。

I changed the function to return the source variable which has been altered in the normalization-function. 我更改了函数以返回在标准化函数中已更改的source变量。 All elements get marked or altered in this function and before returning the resultset I remove all elements marked for deletion: 所有元素都在此函数中被标记或更改,在返回结果集之前,我删除了所有标记为删除的元素:

var allNodes = source.selectAll('*');
allNodes.forEach(function(subelement) {
    logocreator.normalizeSvgElement(subelement, viewBox);
});
source.selectAll('[data-removeme="true"]').remove();
return source.selectAll('svg > *');

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

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