How it works...

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 ...

Get HTML5 Canvas Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.