0

I am new to coding. And I am new to stack overflow. Please, please fogive me if I am not following any of the myriad of rules users have to follow around here.

I am trying to move an object on an HTML5 canvas using a javasript code. Instead, it keeps seeming to elongate. Do I have to use a clear function of some sort? When I do that, it seems to make the black square (player) disappear instead.

Here is my code. Any advice/suggestions would be helpful.

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>
PeterMader
  • 5,739
  • 1
  • 16
  • 27

1 Answers1

0

Yes, you have to clear be canvas before you draw the player. Otherwise, the newly drawn reactangle will overlap with the old one, which makes it look like it's elongating.

Use CanvasRenderingContext2D#clearRect to clear the canvas:

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++);
<canvas width="300" height="300"></canvas>

As you can see, I refactored your code a bit, for example using window.requestAnimationFrame.

PeterMader
  • 5,739
  • 1
  • 16
  • 27
  • thank you again for your kind and quick responses. Apologies if this post was inappropriate... please do let me know what I can do to avoid getting down-voted. – user8391116 Aug 04 '17 at 18:25
  • I guess the reason for the downvote was that you didn't include the code in your question. It's easier to help you if you give us a short code snippet and a specific problem. That's what AGE meant with the [mcve]. But don't worry too much, you'll get used to it. StackOverflow has strict rules, but a great community. For a start, you could read [ask] and take the [tour]. I hope my answer helped you. – PeterMader Aug 04 '17 at 18:40