如何获取SVG折线元素的长度? [英] How can I get length of SVG polyline element?

查看:465
本文介绍了如何获取SVG折线元素的长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This is my polyline and I want to get its length.

<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读取每个顶点位置,然后使用毕达哥拉斯定理确定顶点之间的距离.然后将所有距离相加.

Use the SVG DOM to read each vertex position and then work out the distance between the vertices using pythagoras theorem. Then add up all the distances.

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>

这篇关于如何获取SVG折线元素的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆