gpt4 book ai didi

javascript - 需要 JS 图像事件监听器在 html5 Canvas 上绘制多个图像的帮助

转载 作者:行者123 更新时间:2023-11-28 06:47:02 25 4
gpt4 key购买 nike

请帮助新手!我想在 Canvas 中显示:后图像,后跟前图像,然后是绿色矩形。当它运行时,它不会显示全部。当我反复单击“刷新”按钮时,我可以立即看到绿色矩形,但被后面的图像覆盖。单击“刷新”时,正面图像偶尔会出现。我希望能够按顺序显示,并稍后在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");

}

关于javascript - 需要 JS 图像事件监听器在 html5 Canvas 上绘制多个图像的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33325342/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com