Canvas & SVG: Canvas Images and Videos - JUMP START HTML5 (2014)


Chapter 16 Canvas & SVG: Canvas Images and Videos

You can use bitmap images and video with canvas. In this chapter, we’ll look at how you can copy images and videos onto your canvas.


You can copy a pre-defined bitmap image to your canvas using the drawImage() method. The same method can also be used to draw part of an image or alter its size. You can position the image on the canvas much in the same way as you would draw a line:

var c = document.getElementById("MyCanvas");

var ctx=c.getContext("2d");

var img = document.getElementById("yourimage");


As you can see here, the image (which is on our page with the ID "yourimage") is positioned at the x,y coordinates passed in the method: ctx.drawImage(img,x,y).

You can specify the size of the image by adding width and height, like this:


To crop the image and position the cropped part only:


In the code above, the sx and sy coordinates dictate where to begin cropping the image, and swidth and sheight dictate the dimensions of the image.

Using the image() Object

The above example assumes that the image is on the page already. You may find it preferable to load the image dynamically using JavaScript.

// canvas set-up

var canvas = document.getElementById('MyCanvas');

var ctx = canvas.getContext('2d');

// load image from a URL

var img = new Image();

img.src = "";

// is image loaded?

if (img.complete) addToCanvas();

else img.onload = addToCanvas;

// add image to canvas

function addToCanvas() {




The content of an HTML5 video element can also be copied to a canvas. You may want to do this so you can overlay additional text or apply processing effects.

var video = document.createElement("video");

video.src = "yourvideo.mp4";

video.controls = true;

In order to then draw the video to canvas, you'll need to add a handler for the video's onplay event, which copies the current video frame.

var canvas = document.getElementById('MyCanvas')

var ctx = canvas.getContext('2d');

// set canvas dimensions to same as video

video.onplay = function() {

canvas.width = video.videoWidth;

canvas.height = video.videoHeight;



// copy frame to canvas

function draw() {

if(video.paused || video.ended) return false;

ctx.drawImage(video, 0, 0);

setTimeout(draw, 20);


// start video playback;