在画布上移动多个元素并清除矩形

时间:2017-01-07 23:43:59

标签: javascript canvas

我有一个问题,例如我有2个对象,我使用键盘事件做了一些移动的东西。现在的问题是,我不知道何时清除画布,以便我可以保留它们的多个实例,也可以单独移动它们。

const canvas = document.getElementById('canvas-game');
const context = canvas.getContext('2d');

// Set Canvas To Whole Screen
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;

// Player
class Player {
  constructor(xPosition = 0, yPosition = 0, height = 25, width = 25) {
    this.xPosition = xPosition;
    this.yPosition = yPosition;
    this.height = height;
    this.width = width;
    this.moveEvents = this.moveEvents.bind(this);
  }

  draw() {

    // this.clear();

    let { xPosition, yPosition, height, width} = this;

    context.beginPath();
    context.rect(xPosition, yPosition, height, width);
    context.closePath();    
    context.fill();

    // Bind Events
    this.initEvents();
  }

  initEvents() {
    canvas.addEventListener('keydown', this.moveEvents);
  }

  clear() {
    context.clearRect(0, 0, canvas.height, canvas.width);
  }

  moveEvents(event) {
    let keyPressed = event.keyCode;

    if (keyPressed === 38 || keyPressed === 87) {
        this.yPosition -= 5;
    } else if (keyPressed === 40 || keyPressed === 83)  {
        this.yPosition += 5;
    } else if (keyPressed === 37 || keyPressed === 65)  {
        this.xPosition -= 5;
    }  else if (keyPressed === 39 || keyPressed === 68)  {
        this.xPosition += 5;
    }

    this.draw();
  }

}

// Enemy
class Enemy extends Player {
  constructor() {
    super();
  }
}

function update(...components) {
  components.forEach((item) => {    
    item.draw();
  });
}

function init() {
  let player = new Player(100, 100);
  let player2 = new Player(200, 200);

  update(player, player2);
}


init();

它按原样工作,但在更新时会留下痕迹。非常感谢。

在此演示:jsFiddle

1 个答案:

答案 0 :(得分:0)

  1. clear函数移出Player类(与update相同的上下文),因为它不应负责清除全局canvas < / LI>
  2. 在玩家的平局调用之前,在clear函数中调用update,例如

    function update(...components) {
      clear();
      components.forEach((item) => {
        item.draw();
      });
    }
    
  3. 使用全局draw函数替换moveEvents函数中的update调用,因为您希望在每次移动后重新绘制整个场景(因为您需要清除整帆布)