Why does this object not move?

时间:2019-05-19 03:57:28

标签: javascript canvas html5-canvas

I'm new to Javascript and I've tried to make a simple game where there's a block and it can move. Right now, I've only made it so that it so that it should only move left, but it doesn't.

I've checked for typos and I've checked the console with console.log and it works, but my object doesn't move.

const ctx=document.getElementById("ctx").getContext("2d");

var one={
  width:30,
  height:30,
  x:250,
  y:200,
  color:"rgb(63, 154, 244)"
};
function draw(){
  ctx.save();
  ctx.fillStyle=one.color;
  ctx.fillRect(one.x,one.y,one.width,one.height);
  ctx.restore();
}
function move(){
  document.onkeydown=function(event){
    if(event.keyCode==65){
      one.x=one.x-15;
      console.log("test");
    }
  }
}

function startGame(){
  draw();
  setInterval(move,2000);
}
startGame();
<canvas id="ctx" width="1400" height="500" style="border:0.01em solid #fff"></canvas>

I thought that by pressing "a", the block would move left by 15, but it doesn't move. It still shows up as the blue color, but it just doesn't move.

1 个答案:

答案 0 :(得分:0)

Here's a sample modification on your code, you can improve it.

const ctx=document.getElementById("ctx").getContext("2d");

var one={
  width:30,
  height:30,
  x:250,
  y:200,
  color:"rgb(63, 154, 244)"
};

function draw(){
  ctx.save();
  ctx.fillStyle=one.color;
  ctx.fillRect(one.x,one.y,one.width,one.height);
  ctx.restore();
}

// we're gonna register our event handler just one time.
document.onkeydown=function(event){
  if(event.keyCode==65){
    moveLeft();
  }
}

function moveLeft() {
  // I've added this line of code to erase the previous square from the canvas
  // Since we're gonna move your square to another location.
  // You'll probably want to move this code somewhere else
  // Can be inside a redraw function? Idk.
  ctx.clearRect(one.x, one.y, one.width, one.height);
  one.x=one.x-15;
  console.log("test");
}

function startGame(){
  // Let's call draw every 50ms
  setInterval(draw,50);
}

startGame();

I moved the setting of onkeydown callback outside, so it will be there from the start.

And in the startGame(), instead of calling the former function move repeatedly with an interval, I called draw since we want to redraw the canvas to update the game visually.

The problem with your code was:

  1. In your startGame, you were repeatedly calling move every 2 seconds, in which, the function just registers an event handler to document.onkeydown, it doesn't really do anything.

  2. Since the handler is being registered, you can assure that the value of one.x really updates when pressing the A key, you can't just validate it because the canvas never updates.

Here is a working JSFiddle: https://jsfiddle.net/8qjcfya9/

UPDATE

I just refactored some part of the code, still works the same.