为什么我的物体伸长而不是移动?

时间:2017-08-04 17:30:40

标签: javascript html5

我是编码的新手。我是新的堆栈溢出。如果我没有遵循用户必须遵循的无数规则,请嘲笑我。

我正在尝试使用javasript代码在HTML5画布上移动对象。相反,它似乎一直在延长。我是否必须使用某种明确的功能?当我这样做时,它似乎使黑方(玩家)消失了。

这是我的代码。任何意见/建议都会有所帮助。

var c;
var ctx;
var playerPosX = 90;
var playerPosY = 90;

function init(){
  c = document.getElementById("c");
  ctx = c.getContext('2d');
  ctx.fillStyle = 'red';
  ctx.fillRect(0,0,200,200);
  setInterval (player, 10);
  }


function player(){
  c=document.getElementById("c");
  ctx= c.getContext('2d');
  ctx.fillStyle='black';
  ctx.fillRect(playerPosX,playerPosY,20,20);
}

init();
function doKeyDown (evt){
  switch (evt.keyCode) {
    case 40:
      playerPosY=playerPosY+1;
      break;
    }
}

document.addEventListener('keydown', doKeyDown, true);
<canvas id="c" width="300" height="300"></canvas>

1 个答案:

答案 0 :(得分:0)

是的,在绘制播放器之前必须先清除画布。否则,新绘制的反应角将与旧的反应角重叠,这使它看起来像是在伸长。

使用CanvasRenderingContext2D#clearRect清除画布:

&#13;
&#13;
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
let playerPosX = 90;
let playerPosY = 90;

function draw () {
  window.requestAnimationFrame(draw);

  // clear the canvas
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  
  // draw the background
  ctx.fillStyle = 'red';
  ctx.fillRect(0, 0, 200, 200);
  
  // draw the player
  ctx.fillStyle = 'black';
  ctx.fillRect(playerPosX, playerPosY, 20, 20);
}

window.requestAnimationFrame(draw);
document.addEventListener('keydown', e => e.key === 'ArrowDown' && playerPosY++);
&#13;
<canvas width="300" height="300"></canvas>
&#13;
&#13;
&#13;

如您所见,我稍微重构了您的代码,例如使用window.requestAnimationFrame