Created
November 5, 2022 19:00
-
-
Save hbi99/437389c01d2ddff5739fed1896cadfc1 to your computer and use it in GitHub Desktop.
Fit SVG into viewbox
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let dim = [...svg.children].filter(el => el.getBBox).reduce((acc, el) => { | |
let { x, y, width, height } = el.getBBox(); | |
if (!acc.min.x || x < acc.min.x) acc.min.x = x; | |
if (!acc.max.x || x + width > acc.max.x) acc.max.x = x + width; | |
if (!acc.min.y || y < acc.min.y) acc.min.y = y; | |
if (!acc.max.y || y + height > acc.max.y) acc.max.y = y + height; | |
return acc; | |
}, { min: {}, max: {} }), | |
viewBox = `${dim.min.x} ${dim.min.y} ${dim.max.x - dim.min.x} ${dim.max.y - dim.min.y}`; | |
svg.setAttribute("viewBox", viewBox); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment