The following code should display an image in a grid when I click the button. The issue is I have to click the button twice in order to see the images. I get the log output on both function calls, even when the images don’t show up. What’s going on?
EDIT: I’ve found out that the problem only occurs when chrome developer tools is open, so it’s not a javascript problem.
EDIT2: In addition to the accepted answer, this link helped me: Javascript Canvas Element – Array Of Images
<html>
<head>
<title>Canvas Test</title>
<script>
function init() {
var canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
images = new Array();
}
function drawImage() {
for (var i = 0; i < 12; i++) {
for (var j = 0; j < 12; j++) {
var index = i*12 + j;
images[index] = new Image();
images[index].src = 'image.jpg';
images[index].onload = function(image, index, i, j) {
console.log(index);
context.drawImage(image, i * 20, j * 20, 20, 20);
console.log("Loading image: " + image.src);
} (images[index], index, i, j);
}
}
}
</script>
</head>
<body onload="init();">
<canvas id="canvas" width="300px" height="300px" style="border: solid;"></canvas>
<button onclick="drawImage();">Display Image</button>
</body>
</html>
Actually your code works. But sometimes the picture is not loaded and you will have to click the button twice.
Try it here.
2 problems:
This will fire right way, because
()at the end means to run it. That’s why you have to click it twice.srcshould come last. (MDN) (but actually it doesn’t matter)To fix it, you have to make the function so that it won’t run right away. Also because it is inside a loop and it uses scoped variables, it needs extra care. See code in demo.
>FIXED DEMO!<