获取从 .svg 的“<path>”信息推导出的面积值

get the value of the area deduced from the `<path>` info of a .svg

让我们以这个简单的 .svg 为例:

对于那个形状,我得到了这个代码:

   <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
         width="1000px" height="1000px" viewBox="0 0 1000 1000" enable-background="new 0 0 1000 1000" xml:space="preserve">
    <path d="M1000,500c0,276.143-223.857,500-500,500c-276.143,0-57.729-467.521-313.389-571.889C-252.278,248.944,223.858,0,500,0
        C776.143,0,1000,223.857,1000,500z"/>
    </svg>

我有办法从 .svg 的 <path> 信息中推导出面积值吗?

<path d="M1000,500c0,276.143-223.857,500-500,500c-276.143,0-57.729-467.521-313.389-571.889C-252.278,248.944,223.858,0,500,0
        C776.143,0,1000,223.857,1000,500z"/>

您可以将路径转换为多边形,然后使用 "area of a polygon" 算法。

准确性将取决于您在转换过程中使用了多少点,以及可能累积的任何浮点错误。

我不知道它的准确性与计算像素的方法相比如何。但我希望它更准确。

function calculateAreaOfPolygon(points)
{
  if (points.length < 3)
    return 0;
  var area = 0, n = points.length;
  for (var i=0; i<(n-1); i++) {
    area += points[i].x * points[i+1].y;
    area -= points[i+1].x * points[i].y;
  }
  area += points[n-1].x * points[0].y;
  area -= points[0].x * points[n-1].y;
  return Math.abs(area) / 2;
}

function convertPathToPolygon(pathId)
{
  var pathElem = document.getElementById(pathId);
  var pathLen = pathElem.getTotalLength();
  var numSteps = Math.floor(pathLen * 2);
  var points = [];
  for (var i=0; i<numSteps; i++) {
    var p = pathElem.getPointAtLength(i * pathLen / numSteps);
    points.push(p);
  }
  return points;
}

var pathPointsArray = convertPathToPolygon("mypath");

console.log(calculateAreaOfPolygon(pathPointsArray));
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
         width="1000px" height="1000px" viewBox="0 0 1000 1000" enable-background="new 0 0 1000 1000" xml:space="preserve">
    <path id="mypath" d="M1000,500c0,276.143-223.857,500-500,500c-276.143,0-57.729-467.521-313.389-571.889C-252.278,248.944,223.858,0,500,0
        C776.143,0,1000,223.857,1000,500z"/>
</svg>