我在画布上的图像在页面上启动后就消失了



我的画布中的图像出现了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>

如果你运行它,它会显示一个错误,但在我的页面上没有,它只会出现和消失我正试图为一个学校项目制作一款类似谷歌霸王龙的游戏,但。。。

图像出现后画布会迅速清除。

这是因为属性width和height在setInterval调用的函数中被重置。这可能是有意为之,因为对于动画,画布需要清除,然后在新位置重新绘制任何对象。

但是,在这种情况下,对象不会被重新绘制,因此图像会消失。

这个片段每次都会在新的位置重新绘制图像,作为演示。

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>

最新更新