Image Basics

The Canvas API allows access to the DOM-defined Image object type through the use of the drawImage() method. The image can be defined in HTML, such as:

<img src="ship1.png" id="spaceship">

Or it can be defined in JavaScript. We create a new JavaScript Image instance like this:

var spaceShip = new Image();

We can then set the file source of the image by assigning a URL to the src attribute of our newly created Image object:

spaceShip.src = "ship1.png";

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.