繁体   English   中英

我在 canvas 中的图像在页面启动后消失

[英]My image in the canvas dissapear after startin the page

我在 canvas 中的图像出现 1 秒后消失

 document.addEventListener ('keydown', function(evento){ if(evento.keyCode == 32){ console.log("salta"); } }); var ancho =700; var alto =300; var canvas,ctx; function inicializa() { canvas = document.getElementById('canvas') ctx = canvas.getContext('2d'); cubito = new Image(); cubito.src = "Cubito.png"; cubito.onload = function(){ ctx.drawImage(cubito,0,0,50,50,); } } function borrarCanavas() { canvas.width = ancho; canvas.height = alto; } //Bucle chido:v //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- var FPS = 10; setInterval(function(){ principal(); },1000/10); function principal(){ borrarCanavas(); }
 <html> <head> <script src="juego.js"> </script> </head> <body onload="inicializa();"> <canvas id="canvas" width="700" height="300" style="border:2px solid #000000;"></canvas> </body> </html>

如果你运行它,它会出现一个错误,但在我的页面没有,它只会出现并消失我试图为学校项目制作像谷歌 T-Rex 这样的游戏但是......

canvas 出现图像后会快速清除。

这是因为在 setInterval 调用的 function 中正在重置属性宽度和高度。 这可能是故意的,因为对于 animation,canvas 需要被清除,然后用新位置的任何对象重新绘制。

但是,在这种情况下,object 不会重绘,因此图像会消失。

此片段每次在新的 position 中重绘图像作为演示。

 document.addEventListener ('keydown', function(evento){ if(evento.keyCode == 32){ console.log("salta"); } }); var ancho =700; var alto =300; var canvas,ctx; var x = 0;//for demo var y = 0; function inicializa() { canvas = document.getElementById('canvas') ctx = canvas.getContext('2d'); cubito = new Image(); cubito.src="https://i.stack.imgur.com/zEd65.png"; cubito.onload = function(){ ctx.drawImage(cubito,0,0,50,50,); } } function borrarCanavas() { canvas.width = ancho; canvas.height = alto; x=(x+1)%ancho; y=(y+1)%alto; ctx.drawImage(cubito,x,y,50,50); } //Bucle chido:v //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- var FPS = 10; setInterval(function(){ principal(); },1000/10); function principal(){ borrarCanavas(); }
 <html> <head> <script src="juego.js"> </script> </head> <body onload="inicializa();"> <canvas id="canvas" width="700" height="300" style="border:2px solid #000000;"></canvas> </body> </html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM