我该怎么做才能让程序等待加载图像?(java脚本)



我最近开始学习html,目前正在学习java脚本。我的问题是,我会停止程序,直到加载了一个图像,然后在画布上绘制图像(因为如果没有加载图像,我想在画布上画它,什么都不会显示(。

这是我的代码(放在一个文件中(:

<html>
<head>
<title>dog food</title>
<link rel = "icon" href = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQudx87gpctKJdgDyq5DpVlb12fI3_7XgbfXw&usqp=CAU">
<style>
canvas.GameWindow {
display : block;
margin-left : auto;
margin-right : auto;
}
</style>
</head>
<body>
<canvas width = 600 height = 350 class = GameWindow>Sorry but the canvas is not taken by your web browser</canvas>

<script>
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');

//initialize canvas
/*ctx.fillStyle = 'black';
ctx.fillRect(0, 0, 600, 350);*/

//create function
function drawAnImage(positionX,positionY,width,height,image) {
ctx.drawImage(image, positionX, positionY, width, height);
console.log("an image has been drawn");
};
var img = new Image();
img.src = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQudx87gpctKJdgDyq5DpVlb12fI3_7XgbfXw&usqp=CAU";
img.onload = function() {
console.log("image load");
};
drawAnImage(0,0,100,100,img);
</script>
</body>
</html>

实际上,当我运行代码时,画布上什么都不显示,因为图像是在我调用drawAnImage函数后加载的。

等待它加载回调:

img.onload = function () {
drawImage(0, 0, 100, 100, img);
};

如果加载时出错,你也可以做一些事情:

img.onerror = function () {
alert("Oh no an error!");
};

这里有ES6箭头功能和addEventListener:

img.addEventListener("load", () => {
drawImage(0, 0, 100, 100, img);
});
img.addEventListener("error", () => {
alert("Oh no an error!");
});

所以我最终使用了这个小算法来加载图像:

const imageToLoad = [];
var totalImage = imageToLoad.length;
let imageLoad = [];

for (var i = 0;i<totalImage;i++) {
var img = new Image();
img.src = imageToLoad[i];
imageLoad.push(img);
img.onload = function() {
if (i == totalImage) {
//here i start my game loop
gameLoop(imageLoad);
};
};  
};

那么,什么是价值观呢?第一个valuimageToLoad是放置要使用的图像的位置,imageLoad是查找加载图像的位置。最后,对于对该算法感兴趣的人来说,每次加载图像时,该算法都会查看它是否是最后一个要加载的图像,如果是,在我的情况下,该算法会启动游戏的游戏循环。

最新更新