我有一个bird = {}对象,我定义了一个绘图函数,但是在渲染函数中调用时,图像不会出现。谁能指出我做错了什么?提前谢谢。
编辑:我注意到它并不总是出现的原因是因为屏幕上还有其他的精灵,当我把它们关闭时,鸟总是出现。有什么可以解决这个问题吗?
bird = {
draw:function() {
var birdimg = new Image();
birdimg.onload = function() {
ctx.drawImage(birdimg, -20, height - 200);
}
birdimg.src = "//i.stack.imgur.com/nsZLM.png"; //"assets/bird.png";
}
};
function main() {
canvas = document.createElement("canvas");
//Set the width and height to the sizes of the browser
width = window.innerWidth;
height = window.innerHeight;
//Frames the game if the width is larger than 500
if(width >=500){
width = 320;
height = 480;
canvas.style.border = "1px solid #000";
evt = "mousedown";
}
//Sets the canvas sizes to the width and height variables
canvas.width = width;
canvas.height = height;
ctx = canvas.getContext("2d");
//Set the default state
currentstate = states.Splash;
document.body.appendChild(canvas);
render();
}
function render(){
//Adding bird
bird.draw();
//Loads sky.png
bgimg = new Image();
bgimg.onload = function() {
ctx.drawImage(bgimg,-20,height-200);
ctx.drawImage(bgimg,256,height-200);
}
bgimg.src = "assets/sky.png";
//Loads land img
landimg = new Image();
landimg.onload = function() {
ctx.drawImage(landimg,0,height-100);
}
landimg.src = "assets/land.png";
//Creates rectangle that colors background. THIS IS THE BOTTOM LAYER. WRITE CODE ABOVE
ctx.fillStyle="#4ec0ca";
ctx.fillRect(0,0,canvas.width,canvas.height);
ctx.stroke();
}

答案 0 :(得分:1)
关注@ K3N的建议是一个有效的例子。感谢@ K3N的指导。
通过这些更改,您的代码将如下所示:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script>
// declare vars so they are available outside of main()
var canvas,
ctx,
width,
height;
var bird = {
draw: function() {
var birdimg = new Image();
birdimg.src ="http://www.jqueryscript.net/images/Simplest-Responsive-jQuery-Image-Lightbox-Plugin-simple-lightbox.jpg";
birdimg.onload = function() {
ctx.drawImage(birdimg, -20, height - 200);
};
}
};
function main(){
canvas = document.createElement("canvas");
//Set the width and height to the sizes of the browser
width = window.innerWidth;
height = window.innerHeight;
//Frames the game if the width is larger than 500
if(width >=500){
width = 320;
height = 480;
canvas.style.border = "1px solid #000";
var evt = "mousedown";
}
//Sets the canvas sizes to the width and height variables
canvas.width = width;
canvas.height = height;
ctx = canvas.getContext("2d");
//Set the default state
// "states" is not defined so I'm commenting this out
// var currentstate = states.Splash;
document.body.appendChild(canvas);
render();
}
main();
function render(){
//Adding bird
bird.draw();
}
</script>
</body>
</html>
希望这有帮助, Nick Leoutsakos