Created
October 21, 2016 13:39
-
-
Save john-doherty/2ad94360771902b16f459f590b833d44 to your computer and use it in GitHub Desktop.
Trim whitespace from SVG elements
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
function trimSvgWhitespace() { | |
// get all SVG objects in the DOM | |
var svgs = document.getElementsByTagName("svg"); | |
// go through each one and add a viewbox that ensures all children are visible | |
for (var i=0, l=svgs.length; i<l; i++) { | |
var svg = svgs[i], | |
box = svg.getBBox(), // <- get the visual boundary required to view all children | |
viewBox = [box.x, box.y, box.width, box.height].join(" "); | |
// set viewable area based on value above | |
svg.setAttribute("viewBox", viewBox); | |
} | |
} |
Thankkkyoooouuuuuuuuuuu for sharing this.
Thank you!
Thank you a lot.
You really helped me by far!! Thank you so much :D
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
FYI, calling
getBBox()
only works for inline SVG, not for SVG files embedded using<object>
or<embed>
(at least in my experience -- I got aNS_ERROR_FAILURE
, using Firefox).