删除SVG文件中的空白处

问题描述 投票:0回答:1

我已经下载了200多页SVG文件形式的数据.问题是大部分SVG文件周围都没有使用空格,所以画出来的图非常小.有没有办法把这些空格全部批量删除,然后把SVG文件完整打印出来?

先谢谢你

你可以在这里找到一个代码: pastebin.comrawEJFUuv5A 这是SVG文件之一,但我有更多的SVG文件。我试过使用inkspace来删除空白,但它并不适合我所有的SVG文件,我还试过使用github SVGOMG,但这将需要花费大量的时间来逐一完成。我试过用宏和SVG minifier网站,但试了几次后网站就崩溃了。

svg minify space white
1个回答
1
投票

我希望你所有的svg元素都是以同样的方式构建的。

在这种情况下,所有的svg元素里面的图纸都会被包裹在一组 <g>. 这是非常有用的,因为你可以得到组的边界框,并使用它来构建viewBox属性的值。

// get the svg element. In this case I am using querySelector but if you have several svg elements you may need to use `querySelectorAll` and then loop
let svg = document.querySelector("svg");
// remove the attributes width and height of the svg element because I want to avoid a different aspect ratio
svg.removeAttribute("width");
svg.removeAttribute("height");
// get the wrapping group. This is assuming that there is a group wrapping everighing in the svg element
let g = document.querySelector("g");
// remove the transform attribute that is translating the group. This is assuming that the transform is not rotating or skewing the group
g.removeAttribute("transform");
// get the position (x,y) and the size (width,height) of the bounding box of the group
let bb = g.getBBox();
// use the bounding box of the group to build the viewBox attribute of the svg element
svg.setAttributeNS(null, `viewBox`, `${bb.x} ${bb.y} ${bb.width} ${bb.height}`)
© www.soinside.com 2019 - 2024. All rights reserved.