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.
2 problems:
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);
This will fire right way, because ()
at the end means to run it. That's why you have to click it twice.
src
should 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.