How to add image to canvas

PeeHaa picture PeeHaa · May 15, 2011 · Viewed 245.6k times · Source

I'm experimenting a bit with the new canvas element in HTML.

I simply want to add an image to the canvas but it doesn't work for some reason.

I have the following code:

HTML

<canvas id="viewport"></canvas>

CSS

canvas#viewport { border: 1px solid white; width: 900px; }

JS

var canvas = document.getElementById('viewport'),
context = canvas.getContext('2d');

make_base();

function make_base()
{
  base_image = new Image();
  base_image.src = 'img/base.png';
  context.drawImage(base_image, 100, 100);
}

The image exists and I get no JavaScript errors. The image just doesn't display.

It must be something really simple I've missed...

Answer

Thomas picture Thomas · May 15, 2011

Maybe you should have to wait until the image is loaded before you draw it. Try this instead:

var canvas = document.getElementById('viewport'),
context = canvas.getContext('2d');

make_base();

function make_base()
{
  base_image = new Image();
  base_image.src = 'img/base.png';
  base_image.onload = function(){
    context.drawImage(base_image, 0, 0);
  }
}

I.e. draw the image in the onload callback of the image.