Javascript Canvas clearRect方法的问题

时间:2017-09-19 03:49:07

标签: javascript canvas html5-canvas

我有两个球在游戏敌人和玩家每当我想改变坐标我清楚玩家矩形但由于某些原因敌人消失。有没有人有一些提示怎么办?也许这是因为我做错了制作函数moveleft moveright.if你也看到一些不好的代码请提供提示。

var c = document.getElementById('myCanvas');
var ctx = c.getContext('2d');
var Player1 = {
  x: 150,
  y: 70,
  velX: 20,
  velY: 12,
  hp: 20,
  startAngle: 40,
};
var Enemy = {
  x: 200,
  y: 150,
  velX: 12,
  velY: 12,
  hp: 20,
  startAngle: 40,
};

function drawPlayer1() {
  ctx.fillStyle = "red";
  ctx.beginPath();
  ctx.arc(Player1.x, Player1.y, Player1.startAngle, 0, 2 * Math.PI);
  ctx.fill();
}

function drawEnemy() {
  ctx.fillStyle = "blue";
  ctx.beginPath();
  ctx.arc(Enemy.x, Enemy.y, Enemy.startAngle, 0, 2 * Math.PI);
  ctx.fill();
}

function move(event) {
  // the event.keyCode is Deprecated, use event.code or event.key
  if (event.keyCode == '39' || event.key === ' ') {

    if (Player1.x < c.width - Player1.startAngle) {
      updatePositionRight();
    }
  }
  if (event.keyCode == '37' || event.key == ' ') {

    if (Player1.x > 0 + Player1.startAngle) {
      updatePositionLeft();
    }

  }
  if (event.keyCode == '38' || event.key == ' ') {
    if (Player1.y > 0 + Player1.startAngle) {
      updatePositionUp();
    }

  }
  if (event.keyCode == '40' || event.key == ' ') {

    if (Player1.y < c.height - Player1.startAngle) {
      updatePositionDown();
    }
  }
}

function updatePositionRight() {

  // update Player1's property
  Player1.x += Player1.velX;

  // erase the canva
  ctx.clearRect(0, 0, c.width, c.height);

  // redraw Player1
  drawPlayer1();
}

function updatePositionLeft() {

  // update Player1's property
  Player1.x -= Player1.velX;

  // erase the canvas
  ctx.clearRect(0, 0, c.width, c.height);

  // redraw Player1
  drawPlayer1();
}

function updatePositionDown() {

  // update Player1's property
  Player1.y += Player1.velY;

  // erase the canvas
  ctx.clearRect(0, 0, c.width, c.height);

  // redraw Player1
  drawPlayer1();
}

function updatePositionUp() {

  // update Player1's property
  Player1.y -= Player1.velY;

  // erase the canvas
  ctx.clearRect(0, 0, c.width, c.height);

  // redraw Player1
  drawPlayer1();
}
// bind event
window.addEventListener('keydown', move, false);
// initialize
function drawEntities() {
  drawPlayer1();
  drawEnemy();
}
drawEntities();
<canvas id="myCanvas" width="600" height="600" style="border:1px solid black"></canvas>

1 个答案:

答案 0 :(得分:2)

您还需要使用每个enemy功能重绘updatePositionXXX。目前,在player1来电之后,只会重新clearRect