Reputation:
I have an SVG image and I need to get the center point of all polygons for painting text. I am trying to do this with the below script:
function calculateCenterPoint(areas) {
var maxX = 0,
minX = Infinity,
maxY = 0,
minY = Infinity;
Array.prototype.forEach.call(areas, function (e) {
var i = 0,
coords = e.getAttribute('points').split(',');
while (i < coords.length) {
var x = parseInt(coords[i++], 10),
y = parseInt(coords[i++], 10);
if (x < minX)
minX = x;
if (x > maxX)
maxX = x;
if (y < minY)
minY = y;
if (y > maxY)
maxY = y;
}
});
return {
x: minX + (maxX - minX) / 2,
y: minY + (maxY - minY) / 2
}; }
but it is not working in IE 11, or edge.
Links:
Upvotes: 0
Views: 5685
Reputation: 1088
instead of looking at the points, get the bounding rect of the svg
const el = document.querySelector("path");
const bbox = el.getBoundingClientRect();
const center = {
x: bbox.left + bbox.width / 2,
y: bbox.top + bbox.height / 2
};
or you could do
const bbox = el.getBBox();
Upvotes: 2