As you can see from the preceding code, we need to wait for the page to load before trying to access the canvas tag by its ID. We can accomplish this with the window.onload
initializer. Once the page loads, we can access the canvas DOM element with document.getElementById()
and we can define a 2D canvas
context by passing 2d
into the getContext()
method of the canvas object. As we will see in the last two chapters, we can also define 3D contexts by passing in other contexts such as webgl
, experimental-webgl
, and others.
When drawing a particular element, such as a path, sub path, or shape, it's important to understand that styles can be set at any time, either before or after the element is drawn, but that the style must be applied immediately after the element is drawn for it to take effect, We can set the width of our line with the lineWidth
property, and we can set the line color with the strokeStyle
property. Think of this behavior like the steps that we would take if we were to draw something onto a piece of paper. Before we started to draw, we would choose a colored marker (strokeStyle
) with a certain tip thickness (lineWidth
).
Now that we have our marker in hand, so to speak, we can position it onto the canvas using the moveTo()
method:
context.moveTo(x,y);
Think of the canvas context as a drawing cursor. The moveTo()
method creates a new sub path for the given point. The coordinates in the top-left corner of the canvas are (0,0), and the coordinates in the bottom-right corner are (canvas width, canvas height).
Once we have positioned our drawing cursor, we can draw the line using the lineTo()
method by defining the coordinates of the line's end point:
context.lineTo(x,y);
Finally, to make the line visible, we can use the stroke()
method. Unless, otherwise specified, the default stroke color is black.
To summarize, here's the typical drawing procedure we should follow when drawing lines with the HTML5 canvas API: