Skip to content

Instantly share code, notes, and snippets.

@hbi99
Created November 5, 2022 19:00
Show Gist options
  • Save hbi99/437389c01d2ddff5739fed1896cadfc1 to your computer and use it in GitHub Desktop.
Save hbi99/437389c01d2ddff5739fed1896cadfc1 to your computer and use it in GitHub Desktop.
Fit SVG into viewbox
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