如何摆脱我的角色移动时绘制的图像痕迹?

时间:2013-12-13 16:02:10

标签: javascript

如何摆脱人物移动时绘制的图像痕迹?

var avatarX = 0; //Variable
var avatarY = 267; //Variable
var avatarImage; //Variable
var counter = 1; //Variable
var XWIDTH = 0; //Variable
var WIDTH = 400; //Variable
var dx = 5; //Variable
var tt; //Variable

设置游戏画布的代码

window.addEventListener('keydown', KeyDown);

function setUpGame() {
var gameCanvas = document.getElementById("gameCanvas");
avatarImage = new Image();

avatarImage.src = "img/avatar.png";


gameCanvas.getContext("2d").drawImage(avatarImage, Math.random() * 100, avatarY);
var tt = setInterval(function(){counTer()},1000);
setInterval(handleTick, 25);
}

检测按钮按下的代码

function KeyDown(evt, switchTEMPO) {
  switch (evt.keyCode) {
      case 39: /*Arrow to the right*/
          if(avatarX + dx <WIDTH && avatarX + dx >XWIDTH) {
             avatarX += dx;
          }
        break;
       case 37: /*Arrow to the right*/
          if(avatarX - dx >XWIDTH) {
             avatarX -= dx;
          }
        break;
  }
}

实施计数器的代码

function counTer() {
  if(counter == 60) {
    clearInterval(tt);
  } else {
    counter++;
    gameCanvas.width = 400;
    gameCanvas.getContext("2d").font = "18px Iceland";
    gameCanvas.getContext("2d").textBaseline = "top";
    gameCanvas.getContext("2d").fillText("Seconds: " + counter, 5, 5);
  }
}

将字符绘制到屏幕的代码

function handleTick() {

    gameCanvas.getContext("2d").drawImage(avatarImage, avatarX, avatarY);

}

1 个答案:

答案 0 :(得分:0)

你可能没有清理画布。在绘制下一帧之前,您应该执行以下操作:

// Clear a specific area of the context
context.clearRect (x, y, width, height);

例如,如果您的画布宽度为300px且高度为100px,则

context.clearRect(0, 0, 300, 100);