Search for '{{search_term}}'

SVG Polyline

CMOS is the Code-Maven Open Source podcast that also includes video interviews. Subscribe to this feed RSS feed with your Podcast listener app or via iTunes iTunes.

This is part of the SVG Tutorial and exercises drawing a Polyline in SVG.

examples/js/svg_polyline.js
function draw_polyline() {
    var draw = SVG('polyline_1');
    draw.size(200, 200);
    var p = draw.polyline([
		[10,10],
		[190,10],
		[190,190],
		[20,190],
		[20,20],
		[180,20],
		[180,180],
		[30, 180]
	]);
	p.fill('none').attr({
        'stroke'       : '#FF0000',
        'stroke-width' : '3px'
    });
}

draw_polyline();

Note, typicall a polyline defines an open shape and thus it should not be filled by any color. If I understand it correctly the SVG.js library automatically uses black fill for every shape, including polylines. Therefore if we want our polyline to be not filled, we need to manually set the fill('none').

There are two parameter formats for a polyline. The one that seems so be a lot more useful is the format you see in the solution. In this case we pass an array of two-element arrays. Each one of the two-element arrays is a point in the sapce [x, y] that will be connected.

In the other format we pass a string in which the x,y pairs are separated by a space. In this case the x,y pair should have no spaces around the comma.

So we pass either of the following:

[ [x1,y1],  [x2,y2], [x3, y3], ... ]
'x1,y1 x2,y2 x3,y3 ...'

but this would be incorrect:

x1, y1 ...

A polyline of a snail

in which the points are calculated by a function.

examples/js/svg_polyline_snail.js
function draw_polyline_snail() {
    var draw = SVG('polyline_snail');
    draw.size(200, 200);
	var s = new Array;
	var step = 180;
	var delta = 10;
	var x = 10;
	var y = 10;
	s.push([x, y]);

	while (Math.abs(step) > 10) {
		x += step;
		s.push([x, y]);
		y += step;
		s.push([x, y]);
		step -= delta;
		step *= -1;
		delta *= -1;
	}

    var p = draw.polyline(s);
	p.fill('none').attr({
        'stroke'       : '#00FF00',
        'stroke-width' : '3px'
    });
}

draw_polyline_snail();


Comments

In the comments, please wrap your code snippets within <pre> </pre> tags and use spaces for indentation.
comments powered by Disqus