如何向SVG折线添加坐标?

时间:2014-09-07 02:28:51

标签: html svg hta polyline

如何使用JavaScript为现有SVG折线添加坐标?

<svg height="240" width="700" id='svg'>
    <polyline 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" />
</svg>

我正在使用IE 9(在.hta文件中)并且需要能够动态地将新点附加到折线。目标是能够创建折线图。我提前道歉,我完全不知道如何引用这个属性。对此的任何指导将不胜感激。

2 个答案:

答案 0 :(得分:9)

如果您向折线添加id属性,使其看起来像这样

<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" />

您可以通过document.getElementById

获取对它的引用

最简单的方法是通过“points”属性上的getAttribute / setAttribute来操作它

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

但是最高性能选项是SVG DOM,因为它避免了将数据串行化到字符串中或从字符串中串行化 - 我所知道的所有UAs都在内部将数据存储为浮点数或双精度数而不是字符串。

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

答案 1 :(得分:2)

var polyline= document.getElementById('polyline-id')
  , points = polyline.getAttribute('points');

points += '12, 23'; // example
polyline.setAttribute('points', points );
如果折线已经渲染,则

可能无效,因此您需要使用setAttributeNShttps://developer.mozilla.org/en-US/docs/Web/API/Element.setAttributeNSgetAttributeNShttps://developer.mozilla.org/en-US/docs/Web/API/Element.getAttributeNS

另一种选择是使用某些库,例如http://www.svgjs.com/http://snapsvg.io/