JS图像未显示在画布上
问题描述:
我有一个bird = {}对象,我在其中定义绘图函数,但在渲染函数中调用时不会显示图像。任何人都可以指出我做错了什么?提前致谢。JS图像未显示在画布上
编辑:我已经注意到它并不总是出现的原因是因为屏幕上还有其他精灵,当我将它们关闭时,鸟总是出现。有什么可以解决这个问题吗?
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();
}
答
继这里@ 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>
希望这有助于 尼克Leoutsakos
的main()不会被调用? “状态”不存在,资产只存在于本地计算机上(您需要上传)。还要考虑使用变量来存储值。 – K3N
我没有写在这里,但它是在原来的代码。关于原来的问题,你有什么好意思的建议吗? – UpARiver
您可以上传鸟图像(使用编辑器中的图片上传按钮),并将img src链接到该图片上,以便我们检查鸟是否绘制在画布区域之外。同时还要减少包含在问题中的例子,以便它可以运行(不使用'states',或者至少使用定义的状态,调用main()等)。 – K3N