1

I've created this function to draw circles:

function draw(x, y, m) {
  i += 1;
  c.beginPath();
  c.arc(x, y, m, 0, Math.PI * 2, false);
  c.strokeStyle = 'white';
  c.stroke();
  c.fillStyle = "white";
  c.fill();
}

I use it to create circles in random places with this function:

function animator() {
  var x = Math.random() * window.innerWidth;
  var y = Math.random() * window.innerHeight;
  var m = Math.floor(Math.random() * 5)

  window.requestAnimationFrame(animator);

  draw(x, y, m);
}

This will keep adding circles. However, eventually when reaching 200 circles, I want to delete 1 shape each time I add a new one. My idea was to do this through adding up the i until reaching 200. Then make and if/else statement based on that.

for (var i = 0; i < 200; i++) {
  draw();
}

However, I don't know how to delete shapes.

Jonathan
  • 8,771
  • 4
  • 41
  • 78
hyenax
  • 157
  • 1
  • 9
  • Possible duplicate of [HTML5 Remove previous drawn object in canvas](https://stackoverflow.com/questions/16969787/html5-remove-previous-drawn-object-in-canvas) – Daniel Beck Nov 04 '18 at 14:19

1 Answers1

2

The way you handle this is by redrawing the canvas every frame.
In the beginning of your frame you clear the canvas and then you redraw your objects. This way it becomes really easy to manage your objects in simple data structures like arrays.

const canvas = document.querySelector('canvas');
const context = canvas.getContext('2d');

function getRandomNumber(min, max) {
  return Math.random() * (max - min) + min;
}

class Circle {
  constructor(centerX, centerY, radius) {
    this.centerX = centerX;
    this.centerY = centerY;
    this.radius = radius;
  }

  draw() {
    context.beginPath();
    context.arc(this.centerX, this.centerY, this.radius, 0, 2 * Math.PI, false);
    context.fillStyle = 'white';
    context.fill();
    context.lineWidth = 2;
    context.strokeStyle = 'red';
    context.stroke();
  }
}

function createRandomCircle() {
  const x = getRandomNumber(0, canvas.width);
  const y = getRandomNumber(0, canvas.height);
  const r = getRandomNumber(5, 10);

  return new Circle(x, y, r);
}

// We manage all circles here
const circles = [];

function gameLoop() {
  // Clear the canvas
  context.clearRect(0, 0, canvas.width, canvas.height);

  if (circles.length > 200) {
    circles.shift();
  }

  // Add a circle
  circles.push(createRandomCircle());

  // Let every object draw itself
  circles.forEach(c => c.draw());
}

// Start the loop
window.setInterval(gameLoop, 50);
canvas {
  width: 100%;
  height: 100%;
  background: black;
}
<canvas></canvas>
Jonathan
  • 8,771
  • 4
  • 41
  • 78