2

I want to make a rectangle that moves from the right to the left.

I could draw a new rectangle in the left of the previous one but i couldn't erase the previous one.

Here is my code:

let cvs = document.getElementById("canvas");
let ctx = cvs.getContext('2d');
let firstpos = 400;

let blocks = [];
blocks[0] = {
  x: 400,
  y: Math.floor(Math.random() * 360)
}

function draw() {
  for (var i = 0; i < blocks.length; i++) {
    ctx.beginPath()
    ctx.fillStyle = "white";
    ctx.fillRect(blocks[i].x, 0, 70, blocks[i].y);
    ctx.fill();
    blocks[i].x -= 0;
  }
  requestAnimationFrame(draw);
}
draw()
#canvas {
  background-color: #000;
}
<canvas id="canvas" width="1000" height="500"></canvas>
ggorlen
  • 44,755
  • 7
  • 76
  • 106
ra fik
  • 92
  • 8

2 Answers2

1

Working snippet

Take advantage of CanvasRenderingContext2D.clearRect()

let cvs = document.getElementById("canvas");
let ctx = cvs.getContext('2d');
let firstpos = 400;

let blocks = [];
blocks[0] = {
  x: 0,
  y: Math.floor(Math.random() * 360)
}

function draw() {
  blocks[0].x++;
  ctx.clearRect(0, 0, canvas.width, canvas.height); // canvas clear up
  for (var i = 0; i < blocks.length; i++) {
    ctx.beginPath()
    ctx.fillStyle = "white";
    ctx.fillRect(blocks[i].x, 0, 70, blocks[i].y);
    ctx.fill();
    blocks[i].x -= 0;
  }
  
  requestAnimationFrame(draw);
}
setInterval(draw, 500)
#canvas {
  background-color: #000;
}
<canvas id="canvas" width="1000" height="500"></canvas>
Mosè Raguzzini
  • 15,399
  • 1
  • 31
  • 43
0

It's not possible to "undraw" something in canvas. However, you can clear the canvas on each frame with clearRect and re-draw everything in a new position.

Additionally, the current code uses blocks[i].x -= 0; which won't change the animation state even with a clear and redraw.

Parameters to fillRect appear incorrect or mislabeled. ctx.fillRect(blocks[i].x, 0, 70, blocks[i].y); should be ctx.fillRect(blocks[i].x, blocks[i].y, width, height);. There's also no need for creating a path or calling fill for this method.

It's typical to encapsulate all data for a block inside the object. We need a color, speed and x/y/height/width.

Note that y: Math.floor(Math.random() * 360) can result in a height of zero.

Here's a simple example of moving a block on the canvas:

const cvs = document.getElementById("canvas");
cvs.width = innerWidth;
cvs.height = innerHeight;
const ctx = cvs.getContext("2d");
const blocks = [{
  x: innerWidth - 50,
  y: 20,
  velocityX: -1,
  width: 50,
  height: 50,
  color: "white"
}];

(function draw() {
  ctx.clearRect(0, 0, cvs.width, cvs.height);
  
  for (const block of blocks) {
    ctx.fillStyle = block.color;
    ctx.fillRect(block.x, block.y, block.width, block.height);
    block.x += block.velocityX;
  }
  
  requestAnimationFrame(draw);
})();
#canvas {
  background-color: #000;
}
<canvas id="canvas"></canvas>
ggorlen
  • 44,755
  • 7
  • 76
  • 106