4

I have a javascript function like this:

function drawImage(canvas, image_source, dx, dy) {
  image = new Image();
  image.src = image_source;  
  image.onload = function() {
    c=canvas.getContext("2d");
    c.drawImage(image,dx,dy,100,100);
  }
}

When I call this function twice in a row, eg:

drawImage(canvas, "foo.jpg", 0, 0);
drawImage(canvas, "bar.jpg", 0 ,100);

bar gets painted twice, once at 0, and once at 100
If I switch the order so that foo is called last, foo gets painted twice.

I've tried to use an array for the images as in "c.drawImage(images[loaded++], dx, dy, 100, 100" and the two images paint separately, but their orders are random.

Is there any way to use a function like this to paint images on a canvas?

Chris
  • 43
  • 2

1 Answers1

7

Try changing:

image = new Image();

to:

var image = new Image();

Currently you're setting "image" in the global scope, then potentially rewriting its onload handler before the load (which doesn't happen synchronously) has happened.

Ben Regenspan
  • 10,058
  • 2
  • 33
  • 44
  • 3
    Note that you also should/must [set `onload` _before_ setting `src`](http://stackoverflow.com/questions/4776670/should-setting-an-image-src-to-dataurl-be-available-immediately). – Phrogz Feb 16 '11 at 03:07
  • Good answer @Ben. Yes without var you're setting a global variable, which then gets overwritten by 'bar'. – Sunday Ironfoot Feb 16 '11 at 09:19
  • Thanks Ben and everyone else for the comments. Adding the var fixed the error. Time to learn a bit more about scope in javascript. – Chris Feb 16 '11 at 16:14