0

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
    }
1
  • 1
    canvas is a drawing system, you cannot move a drawing inside your canvas, you have to erase it and redraw a new one elsewhere. Or use SVG Commented Apr 7, 2021 at 23:51

1 Answer 1

1

You need to clear the canvas.

The easiest way is to draw a rectangle over entire canvas (assuming it's a white background)

ctx.fillStyle = "white";
ctx.fillRect(0, 0, width, height);

or if it is transparent...

ctx.clearRect(0, 0, width, height);

You will need to do this on every frame.

const ctx = window.canvas.getContext("2d");

function clearCanvas() {
  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}

function rectangle(x, y) {
  ctx.beginPath();
  ctx.fillStyle = "red";
  ctx.rect(x, y, 15, 10);
  ctx.stroke();
}

function randomMove() {
  var myVar;
  var x;
  var y;
  x = Math.floor(Math.random() * ctx.canvas.width) + 1;
  y = Math.floor(Math.random() * ctx.canvas.height) + 1;
  rectangle(x, y);
}

function draw() {
  clearCanvas();
  randomMove();
}

myVar = setInterval(draw, 200);
draw();
<canvas id="canvas"></canvas>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.