请帮助新手!我想在画布上显示:后方图像,后面是正面图像,后面是绿色矩形。当它运行时,它不显示所有。当我在“刷新”按钮上反复点击时,我可以立即看到绿色矩形,但被后方图像覆盖。单击“刷新”时,前图像偶尔出现。我希望能够按顺序显示,并稍后在drawScreen中操作元素。我想我不理解“addEventListener”heirarchy。请注意尝试使用drawScreen强制绘制预期的绘图序列...但无济于事。帮助
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<canvas id="myCanvas" width="900" height="484" style="border:2px solid #000000;">
<script type="text/javascript" src="external.js"></script>
</body>
</html>
------------------------------
external.js:
------------
window.addEventListener("load", eventWindowLoaded, false);
function eventWindowLoaded () {
canvasApp();
}
function canvasApp() {
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var theBackImage = new Image();
theBackImage.src = "supportArt/backImg.jpg";
theBackImage.addEventListener("load", function(){context.drawImage(theBackImage, 0, 0, 900, 484)}, false);
var theFrontImage = new Image();
theFrontImage.src = "supportArt/frontImg.jpg";
theFrontImage.addEventListener("load", function() {context.drawImage(theFrontImage, 20, 20, 20, 20)}, false);
drawScreen();
function drawScreen(){
context.drawImage(theBackImage, 0, 0, 900, 484)
context.drawImage(theFrontImage, 20, 20, 20, 20)
context.fillStyle = '#00ff00';
context.fillRect(50, 50, 50, 50)
}
}
答案 0 :(得分:0)
在第一次调用绘制所有内容之前,您不是在等待所有图像加载,然后在加载图像时自己绘制图像,这可能是任何顺序。
在开始绘图之前,您需要等到所有资源都已加载。
我已经修改了你的代码。它会计算您要加载的图像数量,并等待许多图像在调用绘图之前加载。
function canvasApp() {
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var imagesToLoad = 0; // number of images that you are loadin
var imagesLoaded = 0; // the number of images loaded
function drawScreen() { // draw the stuff
context.drawImage(theBackImage, 0, 0, 900, 484)
context.drawImage(theFrontImage, 20, 20, 20, 20)
context.fillStyle = '#00ff00';
context.fillRect(50, 50, 50, 50)
}
var loaded = function(){ // event for image on load
imagesLoaded += 1; // add the image to the loaded count
if(imagesLoaded === imagesToLoad){ // when the load count is the same as the images to load
drawScreen(); // all load so draw;
}
}
var loadImage = function(url){ // load an image
var image = new Image();
image.addEventListener("load",loaded);
imagesToLoad += 1; // add to the number of images we want to load
image.src = url;
return image; // return the image;
}
var theBackImage = loadImage("supportArt/backImg.jpg");
var theFrontImage = loadImage("supportArt/frontImg.jpg");
}