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.