Skip to content

Instantly share code, notes, and snippets.

@tobozo
Last active November 10, 2019 02:58
Show Gist options
  • Save tobozo/7b87350e57c072ec9046c94ff18080bb to your computer and use it in GitHub Desktop.
Save tobozo/7b87350e57c072ec9046c94ff18080bb to your computer and use it in GitHub Desktop.
I coded this to have lighter coord values in SVG path where the viewBox was excessively high. Resulting code is 20% lighter.
const svgTag = document.querySelector("svg");
const viewBox = svgTag.getAttribute('viewBox');
const elements = svgTag.querySelectorAll("path");
const ratio = 1/10; // changes this until broken paths appear
const charIsNumeric = function( char ) {
return (char >= '0' && char <= '9');
}
const multiplyValues = function( content ) {
let out = '';
let chars = (content+' ').split('');
let buffer = '';
let buffercomplete = false;
chars.forEach(function(char) {
const isNumeric = charIsNumeric( char );
if ( isNumeric ) {
buffer+=''+char;
} else {
if( buffer != '') {
out += '' + parseInt((0- -buffer)*ratio);
buffer = '';
out += char;
} else {
out += char;
}
}
});
if( out[out.length-1] == ' ' ) {
var temp = out.split('');
temp.pop();
out = temp.join('')
}
return out;
}
svgTag.setAttribute('viewBox', multiplyValues( viewBox ) );
elements.forEach( function(element) {
let dcode = element.getAttribute('d');
rcode = multiplyValues( dcode );
element.setAttribute('d', rcode);
if( element.getAttribute('stroke-width') ) {
element.setAttribute('stroke-width', element.getAttribute('stroke-width')*ratio);
}
console.log({'in':dcode,'out':rcode})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment