请帮助新手!我想在画布上显示:背面图像,然后是正面图像,然后是绿色矩形。当它运行时,它不会显示全部。当我反复单击“刷新”按钮时,我可以看到绿色矩形片刻,但被背面图像覆盖。单击“刷新”时,正面图像偶尔显示。我希望能够按顺序显示,并在以后操纵drawScreen中的元素。我想我不了解“ addEventListener”层次结构。注意尝试使用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)
}
}
您无需等待所有图像加载,然后再进行第一次调用“绘制所有内容”,然后在加载图像时自行绘制图像,可以是任意顺序。
您需要等到所有资源都装入后才能开始绘制。
我已经修改了您的代码。它计算要加载的图像数量,并等待直到加载了许多图像后才调用绘图。
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");
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句