我正在编写一个游戏
我有以下设置:
HTML game.html
<canvas id="canvas" width="288" height="512"></canvas>
<script src="game.js"></script>
JAVASCRIPT game.js
var document;
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
//load images
var pipeNorth = new Image();
pipeNorth.src = "images/pipeNorth.png";
function draw(){
/*code */
alert(pipeNorth.height);
requestAnimationFrame(draw);
}
draw();
PROBLEM
如果我设置了一个显示图像高度的警报,它会在前两三个警报中显示0
,然后开始显示实际高度。
这一切为什么要发生?我该如何解决这个问题?我认为这意味着当游戏开始时图像没有完全加载?
发布于 2018-06-07 05:50:24
根据我的经验,这种情况的发生是因为文档呈现需要一些时间。我在这种情况下的技术是时间延迟:
function draw(){
var delay = 200;//Your delay in milliseconds
setTimeout(function(){
/*code */
alert(pipeNorth.height);
requestAnimationFrame(draw);
},delay);
}
它对你有用吗?
发布于 2018-06-07 05:37:14
是的,你是对的,当游戏begins.to修复这个问题时,图像没有完全加载,你只需要使用"load“事件:
var document;
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
//load images
var pipeNorth = new Image();
pipeNorth.src = "images/pipeNorth.png";
function draw(){
/*code */
alert(pipeNorth.height);
requestAnimationFrame(draw);
}
pipeNorth.addEventListener("load",function(){
//this function will execute when the image is fully loaded
draw();
});
https://stackoverflow.com/questions/50729849
复制相似问题