Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with SVG polygon elements

Tags:

javascript

svg

I'm trying to work with an SVG polygon and javascript. I create a polygon and set its initial point list like this:

var polygon = document.createElementNS('http://www.w3.org/2000/svg','polygon');
polygon.setAttribute("points", "0,0  100,100 200,200");

now what do I do if I want to modify the 2nd point (100,100)? Right now I'm basically reconstructing the whole string again. But can we address "polygon.points" as an array somehow, or is it really just a plain simple string? This can work ok for very simple polygons, but if my polygon eventually has hundreds of point pairs, I'd hate to reconstruct the entire "points" attribute as a string every time I want to modify a single element.

Thanks

like image 458
user246114 Avatar asked Jan 28 '10 03:01

user246114


People also ask

How do you draw a polygon in SVG?

Most of the web browsers can display SVG just like they can display PNG, GIF, and JPG. To draw a polygon in HTML SVG, use the SVG <polygon> element. The <polygon> element creates a graphic containing at least three sides. The points attribute is the x and y coordinates for each corner of the polygon.

What is SVG polygon?

SVG Polygon - <polygon>The <polygon> element is used to create a graphic that contains at least three sides. Polygons are made of straight lines, and the shape is "closed" (all the lines connect up). Polygon comes from Greek. "Poly" means "many" and "gon" means "angle".

How do SVG paths work?

A path is defined in SVG using the 'path' element. The basic shapes are all described in terms of what their equivalent path is, which is what their shape is as a path. (The equivalent path of a 'path' element is simply the path itself.)


1 Answers

You can access the individual point values using the SVG DOM:

var p = polygon.points.getItem(1);
p.x = 150;
p.y = 300;

(Assuming that your UA implements this interface.) See SVGPolygonElement, SVGAnimatedPoints, SVGPointList and SVGPoint.

I find though that using these SVG DOM interfaces (at least for me in Batik, in which I do most of my SVG stuff) is often not faster than just updating the attribute with string manipulation.

like image 149
heycam Avatar answered Oct 06 '22 00:10

heycam