Skip to content

Instantly share code, notes, and snippets.

@wojtekmaj
Last active May 2, 2021 19:52
Show Gist options
  • Save wojtekmaj/83b987f4845f669f98e8bf6c173366e9 to your computer and use it in GitHub Desktop.
Save wojtekmaj/83b987f4845f669f98e8bf6c173366e9 to your computer and use it in GitHub Desktop.
Rounds down values in SVG path
function round(value, decimals) {
return Number(`${Math.round(`${value}e${decimals}`)}e-${decimals}`);
}
function roundPath(path, decimals = 3) {
function roundPathPoint(pathPoint) {
function roundPathPointElement(pathPointElement) {
if (pathPointElement.match(/^[A-Za-z]/)) {
return `${pathPointElement[0]}${pathPointElement.slice(1) && round(pathPointElement.slice(1), decimals)}`;
}
return round(pathPointElement, decimals);
}
const pathPointElements = pathPoint.split(',');
return pathPointElements.map(roundPathPointElement);
}
const pathPoints = path.split(' ');
return pathPoints.map(roundPathPoint).join(' ');
}
@wojtekmaj
Copy link
Author

Good catch @andrewsmallbone. Updated :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment