简体   繁体   中英

How to get center point of svg polygon?

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:

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM