简体   繁体   中英

My image in the canvas dissapear after startin the page

My image in my canvas appear fur 1 sec but then it dissapear

 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>

If you run it, it appears an error but in my page no, it only appear and dissapear Im trying to make a game like the google T-Rex for a school project but...

The canvas clears quickly after the image appears.

This is because the attributes width and height are being reset in the function called by setInterval. This is probably intentional as for an animation the canvas would need to be cleared then redrawn with any objects in their new positions.

However, in this case the object is not redrawn so the image just disappears.

This snippet redraws the image each time in a new position as a demonstration.

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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