Using the document Object to Reference the Canvas Element in JavaScript

We will now make use of the DOM to reference the <canvas> we defined in HTML. Recall that the document object represents every element of an HTML page after it has loaded.

We need a reference to the Canvas object so that we will know where to display the Canvas API calls we will make from JavaScript.

First, we will define a new variable named theCanvas that will hold the reference to the Canvas object.

Next, we retrieve a reference to canvasOne by calling the getElementById() function of document, and passing the name canvasOne, which we defined as the id of the <canvas> tag we created in the HTML page:

var theCanvas = document.getElementById("canvasOne");

Get HTML5 Canvas, 2nd Edition 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.