如何在JavaScript

时间:2016-11-21 17:42:10

标签: javascript canvas

我正在使用纯javascript制作游戏,而clearRect函数无法正常工作,这是代码:

//player's location
var playerX = 250;
var playerY = 325;
document.addEventListener('keydown', function(e) {
  if (e.key === 'w' && playerY >= borderW && movement === true) {
    playerY -= playerSpeed;
    //Clears the head of the Protagonist
    ctx.clearRect(playerX + 2.5, playerY + 2.5, 20, 20);
    //Clears the body of the protagonist
    ctx.clearRect(playerX + 5, playerY + 17.5, 15, 25);
    drawProtagonistFacingUp();
  }
  if (e.key == 'd' && playerX < borderD && movement === true) {
    playerX += playerSpeed;
    ctx.clearRect(playerX, playerY, -200, 200);
    drawProtagonistFacingRight();
  }
  if (e.key == 's' && playerY < borderS && movement === true) {
    playerY += playerSpeed;
    ctx.clearRect(playerX, playerY - 15, 200, 200);
    drawProtagonistFacingDown();
  }
  if (e.key == 'a' && playerX > borderA && movement === true) {
    playerX -= playerSpeed;
    ctx.clearRect(playerX, playerY, 200, 200);
    drawProtagonistFacingLeft();
  }
});

应该发生的事情是当玩家按下w,a,s或d移动时,它会清除屏幕上的旧玩家图像并绘制一个新图像。但是,它现在正在做的只是清除少量的玩家形象。如果可能,一个简单的解决方案会有所帮助。感谢。

1 个答案:

答案 0 :(得分:2)

清除画布。

使用画布设置动画的方式是设置一个由requestAnimationFrame调用的主动画循环函数

function update(time){ // requestAnimationFrame calls this function with the 
                       // argument time. Time is in ms (1/1000th second) but
                       // accurate to 1/1,000,000th second,  0.001ms

    ... your code
    requestAnimationFrame(update); // request the next frame
}
requestAnimationFrame(update); // start the animation

在标准设置下,浏览器会每秒调用该函数60次。

不是跟踪每个对象并清除它然后再渲染它,清除整个画布要简单得多。这可以通过几种方式完成

function update(time){ 
    ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height); // Make all pixels
                                                           // transparent
    // or
    ctx.fillStyle = "black"; // can use solid colour, gradient, or pattern
    ctx.fillRect(0,0,ctx.canvas.width,ctx.canvas.height);
    // or 
    // use a background image
    ctx.drawImage(backgroundImage,0,0,ctx.canvas.width,ctx.canvas.height);
    ... your code
    requestAnimationFrame(update); // request the next frame
}
requestAnimationFrame(update); // start the animation

一旦画布清晰,您就可以按顺序渲染对象,最后一个对象将出现在绘制的对象上。这个approch大大简化了你的动画代码。

相关问题