Drawing lines and shapes

Drawing lines

To draw on the canvas requires placing a "pen", making a line, and then making the line visible. The following methods are used in conjunction with each other:

Name Description
.moveTo(x, y) places the pen at point (x, y)
.lineTo(x, y) forms a line by moving the pen to point (x, y)
.stroke() makes a line appear using lineWidth and strokeStyle

That is, to draw a green line from point (0, 0) to point (10, 20), first the line properties are set, then the pen is placed at (0, 0), next a line is formed from (0, 0) to (10, 20), and then finally the line is made visible. At the end of this sequence of steps, the pen will be at (10, 20).

context.lineWidth = 20;
context.strokeStyle = "green";

context.moveTo(0, 0);
context.lineTo(10, 20);
context.stroke();

Drawing shapes

One way to make a shape is to form a path and then fill it in, using the following methods:

Name Description
.beginPath() starts a new shape
.closePath() closes off the shape formed
.fill() fills what was created

If you wish to provide an outline for a shape, either leave it unfilled, or fill it first and then give the outline (otherwise, the outline may be overwritten by the fill).