How to work with timer in canvas javascript?

  canvas, javascript, random, timer

I need to make a rectangle appear randomly somewhere in the canvas, and then it will need to appear randomly in a new place, but I have one problem, it appears a new one but the previous rectangle stay where it was at the beginning and then there are so many rectangles in the canvas, I need to be only one, this is what I’ve done:

 function rectangle(x,y){
    var ctx
    ctx.beginPath();
    ctx.rect(20, 20, 15, 10);
    ctx.stroke();
    }
 function randomMove(){
    var myVar;
    var x;
    var y;
    x = Math.floor(Math.random() * 10) + 1;
    y = Math.floor(Math.random() * 10) + 1;
    myVar = setInterval( ()=> {rectangle(x,y)}, 5000); // pass the rectangle function
    }

Source: Ask Javascript Questions

LEAVE A COMMENT