Search code examples
javascriptcanvas

Clear canvas after ctx.arc was clicked


So the objective is to place a circle randomly on the screen, and if the circle was clicked, remove this old circle and make a new circle.

I'm having a problem with removing the old point and making a new one. Instead of removing the old one, it keeps it, makes a new circle and eventually does whatever this is after a bit of clicking:

enter image description here

This is how my code looks like:

const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
canvas.style.cursor = "crosshair";
function randSpot() {
  var X = Math.floor(Math.random() * canvas.width) + 10;
  var Y = Math.floor(Math.random() * canvas.height) + 10;
  ctx.arc(X, Y, 5.5, 0, 2 * Math.PI);
  ctx.fillStyle = 'red';
  ctx.fill();
  document.body.addEventListener('click', function(e) {
    if (ctx.isPointInPath(e.clientX, e.clientY)) {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      randSpot()
    }
  });
}
randSpot()

What am I doing wrong and how can I fix it?


Solution

  • You forgot to begin a new path

    ctx.beginPath();
    

    I had to modify the code to make it run in the snippet

    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");
    document.body.appendChild(canvas);
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    canvas.style.cursor = "crosshair";
    
    function randSpot() {
      var X = Math.floor(Math.random() * canvas.width) + 10;
      var Y = Math.floor(Math.random() * canvas.height) + 10;
      ctx.beginPath();
      ctx.arc(X, Y, 5.5, 0, 2 * Math.PI);
      ctx.fillStyle = 'red';
      ctx.fill();
    }
    randSpot()
    
    document.body.addEventListener('click', function(e) {
      // I had to remove the following condition
      // ctx.isPointInPath(e.clientX, e.clientY)
      // because the code didn't wanted to work with the snippet
      // but it's unrelated to the problem
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      randSpot()
    });