HTML5 Canvas: Paths

To create more complex shapes than circles and rectangles, we need to learn how to create paths, so we can have free reign and draw whatever we like. This post will concentrate on drawing paths and shapes with straight lines, and I shall cover curved paths in a future post.

Straight line path

A straight line has only two points to its path: the starting point and the ending point:

HTML portion

The first thing I need to do is move the starting point of the path to where I want it – this is achieved with the moveTo context, which picks up the point and shifts it without creating a path. In my example above, I have moved the start point down 10 pixels from the top of the Canvas but left it butted up to the left. Then I applied the lineTo context to move the path 200 pixels along to the right to create the simple straight horizontal line. A stroke has been applied to make it visible.

Straight line path with multiple points

This next path is more varied, with more points placed in different positions to create a jagged line path:

HTML portion

Immediately, the javascript code becomes much longer. moveTo is used whenever you want to ‘pick the pen up’ and place it somewhere else to start drawing another shape without drawing a line between them. In my example, I drew the shape of the house, the windows, the door and the roof shape all separately, and used moveTo to move from one to the other. Ideally, you’d use drawRect for the rectangle elements, but this is just to show how to complete the whole thing using purely paths.

Filled straight line path shape

This is actually simpler than the previous example, the star shape just uses multiple lineTo contexts to create the star shape, then the shape is closed and filled instead of outlined, as in the previous examples.