0

I have an array of images:

var images = ['1.png', '2.png', '3.png', '4.png', '5.png', '6.png'];

...from which I'm choosing one at random in a for loop:

for (var i = 1; i <= num; i++) {
    var randomNumber = randomIntFromInterval(0, (images.length-1));
    var randomImage = images[randomNumber];
}

I then want to draw the random image to a canvas in the same loop:

for (var i = 1; i <= num; i++) {
    var randomNumber = randomIntFromInterval(0, (images.length-1));
    var randomImage = images[randomNumber];

    var img = new Image
    img.src = randomImage;
    ctx.drawImage(img, x, y, width, height);
}

...using a button:

<button type="button" onclick="drawImages();">Look!</button>

The images are drawn correctly, except for one issue. Nothing is drawn until the second click.

It seems like the images have to be loaded before they can be drawn, and the first click seems to load them. But I don't want the images drawn until the button is clicked. I don't quite understand how to load and draw the images in the same click.

J. Adam Connor
  • 1,694
  • 3
  • 18
  • 35
  • use `img.onload=function(){ ctx.drawImage(img, x, y, width, height);}` instead of just the last line of the loop, but then you'll have to wrap the loop in an IIFE as well, passing `i` into the anon so that it's correct when the image loads. – dandavis Apr 05 '16 at 00:55
  • @dandavis, since he is drawing multiple images in a loop, this may draw the images in the wrong order. I'd reccomend preloading all images and saving a reference to the Image-objects instead of the urls. – Thomas Apr 05 '16 at 01:26

0 Answers0