How do I add coordinates to an SVG polyline?

江枫思渺然 提交于 2019-11-30 15:02:36

If you add an id attribute to the polyline so that it looks like this

<polyline id="polyline-id" points="0, 240 40, 25 60, 40 80, 120 120, 140 200, 180 500, 120 600, 5" style="fill:none;stroke:#000;stroke-width:3" />

you can get a reference to it via document.getElementById

The simplest way is to manipulate it via getAttribute/setAttribute on the "points" attribute

var points = polyline.getAttribute("points");
points += "10, 20";
points.setAttribute(points);

but the highest performance option is the SVG DOM as that avoids serialising the points data to/from a string - all UAs I know of store the data internally as an array of floats or doubles rather than a string.

var svg = document.getElementById('svg');
var point = svg.createSVGPoint();
point.x = 10;
point.y = 20;
var polyline= document.getElementById('polyline-id');
polyline.points.appendItem(point);
Nik Terentyev
var polyline= document.getElementById('polyline-id')
  , points = polyline.getAttribute('points');

points += '12, 23'; // example
polyline.setAttribute('points', points );

may not work if the polyline is already rendered, so you need to use setAttributeNS: https://developer.mozilla.org/en-US/docs/Web/API/Element.setAttributeNS and getAttributeNS: https://developer.mozilla.org/en-US/docs/Web/API/Element.getAttributeNS

an another option is to use some library like http://www.svgjs.com/ or http://snapsvg.io/

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!