Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add coordinates to an SVG polyline?

How do I add coordinates to an existing SVG polyline with JavaScript?

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

I am using IE 9 (in a .hta file) and need to be able to dynamically append new points to the polyline. The goal is to be able to create a line graph. I apologize in advance, I have absolutely no idea how to reference this attribute. Any guidance for this would be greatly appreciated.

like image 341
TK421 Avatar asked Sep 07 '14 02:09

TK421


People also ask

How do I create a SVG polyline?

To draw a polygon in HTML SVG, use the SVG <polyline> element. The <polyline> element is to create a shape that consists of straight lines. The points attribute is the x and y coordinates for each corner.

What is path D in SVG?

The d attribute defines a path to be drawn. A path definition is a list of path commands where each command is composed of a command letter and numbers that represent the command parameters.

What is the difference between polygon and polyline?

Polyline geometries are made up of two or more vertices forming a connected line. Polygon geometries are made up of at least four vertices forming an enclosed area. The first and last vertices are always in the same place.


1 Answers

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", 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);
like image 127
Robert Longson Avatar answered Oct 11 '22 13:10

Robert Longson