(click anywhere to close)
OPEN MENU

[Canvas] Stroke Styles

category: Website | course: Canvas | difficulty:

Last chapter introduced lots of ways to create fancy lines, but their default black, thin stroke is already becoming quite boring. Not only can we use certain properties to make our lines bigger and in different colour, but there are also subtle changes to be made which can have a big impact

Line Width

The size of the line. The default is 1, which makes a stroke only 1px wide. To change this, use

lineWidth = number

ctx.beginPath();
ctx.moveTo(20,20);
ctx.lineTo(80,20);
ctx.lineWidth = 10;
ctx.stroke();

Stroke Colour

The colour of the line. The default is black, to change this use

strokeStyle = value

The value can be any valid CSS colour code, but also a variable that contains a gradient or pattern. You’ll learn how to create those later.

ctx.beginPath();
ctx.moveTo(20,20);
ctx.lineTo(80,20);
ctx.strokeStyle = "red";
ctx.stroke();

Line Cap

The line cap determines how the two end points of a line are styled. The syntax is:

lineCap = value

There are three possible values: butt (default), round and square.

CanvasLineCap
ctx.beginPath();
ctx.moveTo(20,20);
ctx.lineTo(80,20);
ctx.lineWidth = 30;
ctx.lineCap = 'round';
ctx.stroke();

Line Join

This property determines how a point – one where two lines meet or join – is styled. The syntax is:

lineJoin = value

There are three possible values: miter (default), round and bevel. Especially on thicker lines, this can make a huge difference.

CanvasLineJoin
ctx.beginPath();
ctx.moveTo(20,60);
ctx.lineTo(60,20);
ctx.lineTo(100,60);
ctx.lineWidth = 30;
ctx.lineJoin = "bevel";
ctx.stroke();

Miter Limit

The default method for joining lines has the nasty side-effect that it creates very large, sharp corners if the angle between two lines is very small. You can tell the canvas to cut off this so-called miter if it gets too long using an upper bound:

CanvasMiterLimit

miterLimit = number

ctx.beginPath();
ctx.moveTo(20,60);
ctx.lineTo(30,20);
ctx.lineTo(40,60);
ctx.lineWidth = 10;
ctx.miterLimit = 3;
ctx.stroke();

Dashed Lines

Dashed lines are lines consisting of dashes with gaps between them. They deviate a bit from the standard syntax we’ve been using thus far, because they require a method to set the line dash, instead of a property. The syntax is:

setLineDash([dash, gap, …, dash, gap])

You can put as many of those dash-gap pairs as want in there. They basically create a pattern of stroke and no-stroke that is repeated all over the path.

ctx.beginPath();
ctx.moveTo(20,60);
ctx.lineTo(60,20);
ctx.lineTo(100,60);
ctx.lineTo(140,20);
ctx.lineWidth = 5;
//The pattern is short stroke (2), gap (3), long stroke (5), gap (3)
ctx.setLineDash([2,3,5,3]);
ctx.stroke();
CONTINUE WITH THIS COURSE
Do you like my tutorials?
To keep this site running, donate some motivational food!
Crisps
(€2.00)
Chocolate Milk
(€3.50)
Pizza
(€5.00)