当我单击按钮时,以下代码应在网格中显示图像。问题是我必须单击按钮两次才能看到图像。即使图像没有显示,我也会在两个函数调用中获得日志输出。这是怎么回事?
编辑:我发现只有在打开 chrome 开发人员工具时才会出现问题,所以这不是 javascript 问题。
EDIT2:除了接受的答案,这个链接帮助了我: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>