how to shrink / normalize an SVG so it fits in a specific viewbox

Viewed 852

I used dozens of SVGs in my current app, they are all inline and they are all normalized.. meaning that all of them have a viewbox of 0 0 24 24 and the icon fits nicely in the middle

Then this designer just gave me multiple new SVGs and they are not standard.. they have viewboxes of 0 0 1024 1024, 0 0 400 400, 0 0 72 72

I want to normalize them so they all have a viewbox of 0 0 24 24.

I tried opening them in vectr.com and I united the paths and then shrunk them and exported the SVG again and sure enough they are much smaller now, however they do not fit 0 0 24 24 exactly.. I need to trial and error it and for example the 0 0 1024 1024 is now 0 0 48 40

I'm sure there's an editor / tool that could have done a perfect job of shrinking it and centering it in such a way that it would fit 0 0 24 24

How can I go about achieving this easily and simply?

Thank you

2 Answers

I would have never thought of such a use case, but if you have exactly one path as the svg content, my own library pathfit can rewrite the the path in that way. Here is a node.js script:

const Pathfit = require('pathfit');

function shrinkPath (path, viewBox, targetWidth, targetHeight) {
    const pathfitter = new Pathfit({viewBox}, undefined, path);

    return pathfitter.scale_with_aspect_ratio(targetWidth, targetHeight);
}

I wouldn't do such a thing. But if you must, you may change the svg with a different viewBox in a <symbol> and use the symbol in an svg with the desired viewBox.

<svg viewBox="0 0 24 24">
<symbol id="c" viewBox="0 0 400 400">
   <circle r="190" fill="red" cx="200" cy="200"/>
</symbol>
   <use xlink:href="#c" width="24" height="24" />
</svg>

Related