Skip to content

Instantly share code, notes, and snippets.

@hmble
Created December 16, 2021 11:49
Show Gist options
  • Save hmble/03ba8fb63cc4031c2e8cf0ab7dc01ed1 to your computer and use it in GitHub Desktop.
Save hmble/03ba8fb63cc4031c2e8cf0ab7dc01ed1 to your computer and use it in GitHub Desktop.
SVG − remove whitespace
<!-- paste svg(s) here -->
//remove multiple attributes from element
//https://stackoverflow.com/a/50541881
Element.prototype.removeAttributes = function(...attrs) {
attrs.forEach(attr => this.removeAttribute(attr));
}
//round to 2 decimal places
//https://stackoverflow.com/a/11832950
function r(num) {
return Math.round((num + Number.EPSILON) * 100) / 100;
}
//remove svg whitespace
function svgRemoveWhitespace(svg) {
let box = svg.getBBox(),
viewBox = [
r(box.x),
r(box.y),
r(box.width),
r(box.height)
].join(' ');
svg.setAttribute('viewBox', viewBox);
svg.removeAttributes('width', 'height'); //optional
showNewViewbox(svg, viewBox);
}
//show new viewbox output above the svg
function showNewViewbox(el, result) {
let output = document.createElement('div');
let field = document.createElement('input');
let label = document.createElement('label');
let id = 'viewbox';
label.setAttribute('for', id);
label.textContent = 'new viewBox:';
field.id = id;
field.setAttribute('type', 'text');
field.setAttribute('readonly', '');
field.value = result;
field.addEventListener('focus', (e) => e.target.select());
output.classList.add('output');
output.insertAdjacentElement('beforeend', label);
output.insertAdjacentElement('beforeend', field);
el.insertAdjacentElement('beforebegin', output);
}
const svgs = document.querySelectorAll('svg');
svgs.forEach(svg => svgRemoveWhitespace(svg));
*,
*::before,
*::after {
box-sizing: border-box;
}
body {
margin: 0;
font-family: Roboto, sans-serif;
overflow-x: hidden;
}
svg {
display: block;
max-width: 100%;
height: auto;
margin: 1em;
outline: 1px solid #f00; //guidelines
}
.output {
display: flex;
flex-flow: row wrap;
align-items: center;
gap: .25em .5em;
margin: 1em;
& ~ & {
margin-top: 3em; //spacing
}
label {
font-weight: 500;
}
}
<link href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,400;0,500;0,700;1,400;1,500;1,700&amp;display=swap" rel="stylesheet" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment