Skip to content

Instantly share code, notes, and snippets.

@mir4a
Created April 8, 2016 11:54
Show Gist options
  • Save mir4a/aaee8b671bd4fa98d6f1a5bff5fbd593 to your computer and use it in GitHub Desktop.
Save mir4a/aaee8b671bd4fa98d6f1a5bff5fbd593 to your computer and use it in GitHub Desktop.
Normalize svg polygon coordinates relative to viewBox
// For example, if you need to "normalize" viewBox minX, minY to 0,
// like this: was viewBox="-270 265 18 32", became viewBox="0 0 18 32"
// in this case polygon points should be converted into relative to viewBox values
// <polygon points="-268.6,265.8 -268.6,270.8 -258.4,281 -268.6,291.2 -268.6,296.2 -253.4,281" />
// This function will convert those point, it accepts two 3 params: points string, minX and minY
// Use example:
// var normalizedPlygon = svgPolygonNormalizer("-268.6,265.8 -268.6,270.8 -258.4,281 -268.6,291.2 -268.6,296.2 -253.4,281", -270, 265);
// console.log(normalizedPlygon);
// > '1.40,0.80 1.40,5.80 11.60,16.00 1.40,26.20 1.40,31.20 16.60,16.00'
function svgPolygonNormalizer(points, minX, minY) {
var pointsArr = points.split(' ');
var result = [];
for (var i = 0, len = pointsArr.length, xy; i < len; i++) {
xy = pointsArr[i].split(',');
result.push(
(
[
+(parseFloat(xy[0] - minX)).toFixed(2),
+(parseFloat(xy[1] - minY)).toFixed(2)
]
).join(',')
);
}
return result.join(' ');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment