SVG Polygon Generator

OK, so the hexagon generator in the previous post seems a little inadequate in hindsight. So here is the code for a more general, regular, convex polygon.

function polygon(x,y,rad,sides) {
	var path = "M ";
	for (a=0;a<sides;a++) {
		if (a>0) {path = path + "L ";}
		path = path + (x+(Math.sin(2*Math.PI*a/sides)*rad)) + " " + (y-(Math.cos(2*Math.PI*a/sides)*rad)) + " ";
	}
	path = path + "z";
	return path;
}

The code will generate a path string for use in SVG. Call it wherever you normally put a path string as shown in the jQuery SVG example below. It always draws the polygon with its first vertex directly above the centre point. If you want it rotated, you’ll need to apply a transform to it.

$('#svg_div').svg();
var svg = $('#svg_div').svg('get');
// call using polygon(x,y,rad,sides) where x and y are centre co-ordinates
// rad is the radius of the vertices, and sides is the number of sides
svg.path(polygon(70,70,60,3),{stroke: "black", "stroke-width":5, fill: "red",});
svg.path(polygon(140,70,60,4),{stroke: "black", "stroke-width":5, fill: "orange",});
svg.path(polygon(210,70,60,5),{stroke: "black", "stroke-width":5, fill: "yellow",});
svg.path(polygon(280,70,60,8),{stroke: "black", "stroke-width":5, fill: "green",});
svg.path(polygon(350,70,60,13),{stroke: "black", "stroke-width":5, fill: "blue",});

As always, if you right-click the iframe image below, you should be able to bring the complete source for the iframe.

** edit ** Note that the function can be used just as easily with D3 or Raphael or whatever other SVG tool you happen to like. Since it generates a standard SVG path string, the call to the polygon() function can be put anywhere that you’d normally put a path string.

In D3 this would probably be in path.attr( “d” , polygon() ).

Tagged with: , ,
Posted in jQuery SVG, SVG

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>