Paths and lines

By Martin McBride, 2017-04-09
Tags: html canvas
Categories: graphics html canvas

A path is a way to define a general shape which can be made up of lines and curves. A path can be used to create pretty much any shape you want.

Paths themselves aren't visible, they just provide a definition of the shape you want to draw. To make the path visible, you must fill it or stroke it, or both.

A path can also be used to define a clipping region.

Drawing a line

You start a path using the beginPath() function.

To draw a line, you must first call moveTo() to define the start of the line, and then call lineTo() to draw the line.

This creates a simple path. We must call stroke() to actually draw the line.

context.strokeStyle = 'blue';
context.lineWidth = 4;

context.beginPath();
context.moveTo(100, 50);
context.lineTo(200, 50);
context.stroke();

This code draws a line from (100, 50) to (200, 50).

image

Notice that we also set the stroke style and line width to control how the line will look. It doesn't matter whether we do this before or after we define the path, provided we do it before we call stroke.

Drawing connected lines

Here is the code to draw 3 connected lines:

context.strokeStyle = 'blue';
context.lineWidth = 4;

context.beginPath();
context.moveTo(100, 50);
context.lineTo(200, 50);
context.lineTo(150, 150);
context.lineTo(50, 150);
context.stroke();

image

To understand this code, you need to

See also

Sign up to the Creative Coding Newletter

Join my newsletter to receive occasional emails when new content is added, using the form below:

Popular tags

555 timer abstract data type abstraction addition algorithm and gate array ascii ascii85 base32 base64 battery binary binary encoding binary search bit block cipher block padding byte canvas colour coming soon computer music condition cryptographic attacks cryptography decomposition decryption deduplication dictionary attack encryption file server flash memory hard drive hashing hexadecimal hmac html image insertion sort ip address key derivation lamp linear search list mac mac address mesh network message authentication code music nand gate network storage none nor gate not gate op-amp or gate pixel private key python quantisation queue raid ram relational operator resources rgb rom search sort sound synthesis ssd star network supercollider svg switch symmetric encryption truth table turtle graphics yenc