2017-10-09 39 views
0

我有一个SVG图像,我需要获取绘制文本的所有多边形的中心点。我试图用下面的脚本来做到这一点:如何获得svg多边形的中心点?

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 
}; } 

但它不工作在IE 11或边缘。

链接:

回答

1

,而不是着眼于点,得到了SVG的边界矩形

const el = document.querySelector("path"); 
const bbox = el.getBoundingClientRect(); 
const center = { 
    x: bbox.left + bbox.width/2, 
    y: bbox.top + bbox.height/2 
}; 

,或者你可以做

const bbox = el.getBBox(); 
+1

'getBBox()'可能会比'getBoundingClientRect()'更好' –

相关问题