HTML and CSS Reference
In-Depth Information
<p>The canvas element is not suppor-
Now modify script.js in the canvas/js directory to gain access to the can-
vas element from JavaScript. We'll begin by adding a variable that will hold a reference
to the canvas element, which we'll set using the getElementById() method:
var canvas; // variable to hold a reference to the can-
vas element on the page
function init() {
canvas = document.getElementById( "canvas" );
look up the canvas element by its ID
window.onload = init;
Note You may have noticed earlier that document is a property of the window
object, so why isn't the syntax window.document… in the previous code block? The
reason is that the browser will automatically look into the window object when look-
ing up a property or method, so it isn't necessary to prefix all the properties or meth-
ods of the window object with window . For example, console is also a property
of window , but for brevity window is usually left out (although it could be included
with no harm caused).
This gets us access to the canvas element from our script. Let's look at what meth-
ods are defined for the canvas element by looking at its prototype, like we did with the
window object, by accessing constructor.prototype . Edit the script like so:
function init() {
// look up the canvas element by its ID
// log the canvas element's prototype
console.log( canvas.constructor.prototype );
This reveals getContext() , which is the method we need to retrieve the context!
The other method, toDataURL() , is for converting the canvas image data to a URL
Search WWH ::

Custom Search