如何获取 SVG 折线元素的长度?

How can I get length of SVG polyline element?

这是我的折线,我想知道它的长度。

<div class="svg-1">
  <svg version="1.0" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="612.417px" height="274.412px" viewBox="0 0 612.417 274.412" enable-background="new 0 0 612.417 274.412" xml:space="preserve"> 
    <g>
      <defs>
        <rect id="SVGID_1_" y="0" width="612.417" height="274.412" />
      </defs>
      <clipPath id="SVGID_2_">
        <use xlink:href="#SVGID_1_" overflow="visible" />
      </clipPath>
      <polyline class="square-1" clip-path="url(#SVGID_2_)" fill="none" stroke="#B2965F" stroke-width="4" stroke-miterlimit="10" points="
                        276.084,191.912 38.084,191.912 38.084,26.079 589.417,26.079 589.417,191.912 311.417,191.912 311.417,273.412     " />
    </g>
  </svg>
</div>

使用SVG DOM读取每个顶点位置,然后使用毕达哥拉斯定理计算出顶点之间的距离。然后把所有的距离加起来。

var totalLength = 0;
var prevPos;
var polyline = document.getElementById("polyline");
for (var i = 0 ; i < polyline.points.numberOfItems;i++) {
    var pos = polyline.points.getItem(i);
    if (i > 0) {
        totalLength += Math.sqrt(Math.pow((pos.x - prevPos.x), 2) + Math.pow((pos.y - prevPos.y), 2));
    }
    prevPos = pos;
}
alert(totalLength);
<div class="svg-1">
  <svg version="1.0" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="612.417px" height="274.412px" viewBox="0 0 612.417 274.412" enable-background="new 0 0 612.417 274.412" xml:space="preserve"> 
    <g>
      <defs>
        <rect id="SVGID_1_" y="0" width="612.417" height="274.412" />
      </defs>
      <clipPath id="SVGID_2_">
        <use xlink:href="#SVGID_1_" overflow="visible" />
      </clipPath>
      <polyline id="polyline" class="square-1" clip-path="url(#SVGID_2_)" fill="none" stroke="#B2965F" stroke-width="4" stroke-miterlimit="10" points="
                        276.084,191.912 38.084,191.912 38.084,26.079 589.417,26.079 589.417,191.912 311.417,191.912 311.417,273.412     " />
    </g>
  </svg>
</div>

这是javascript代码

function getPolylineLength(polylineElement){
    function dis(p,q){
        return Math.sqrt((p.x-q.x)*(p.x-q.x) + (p.y-q.y)*(p.y-q.y));
    }
    var ps = polylineElement.points, n = ps.numberOfItems, len=0;
    for(var i=1; i<n; i++){
        len += dis(ps.getItem(i-1),ps.getItem(i));
    }
    return len;
}

Polyline 元素实现 SVGGeometryElement 接口,而该接口又具有方法 getTotalLength()。所以你基本上可以这样做(假设你的折线有一个属性id="polyline"):

var polyline = document.getElementById("polyline");
var totalLength = polyline.getTotalLength();

SVGGeometryElement.getTotalLength()