0

This is the part of my code where I need it, but I don't know how to make it infinite times, how do I add the loop? I need to have a rectangle, and when I load the page it should appear in a random position in the canvas, and every 5 seconds a new rectangle should appear in a new position, the rectangles are always the same size

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
    }
2
  • Generate the random numbers inside the interval, not outside, else they'll always be the same x and y Commented Apr 9, 2021 at 6:08
  • add code snippet with your html, it will help others. Commented Apr 9, 2021 at 6:16

2 Answers 2

1

Working example:

var canvas = document.querySelector('canvas');
canvas.width = 300;
canvas.height = 150;
var ctx = canvas.getContext('2d');

setInterval(drawRect, 500, ctx);

function drawRect(ctx) {
  var x = Math.floor(Math.random() * ctx.canvas.width) + 1;
  var y = Math.floor(Math.random() * ctx.canvas.height) + 1;
  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
  ctx.fillStyle = '#ff0000';
  ctx.fillRect(x, y, 15, 10);
}
<canvas></canvas>

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

Comments

0

What you need is to call your randomMove function recursively; This way, you will generate that infinite loop which will render new rectangles each 5 seconds:

function randomMove() {
  const x = Math.floor(Math.random() * 10) + 1;
  const y = Math.floor(Math.random() * 10) + 1;

  rectangle(x,y); // Define rectangle

  setTimeout(() => {
    randomMove() // Wait 5s before iterating recursively
  }, 5000)
}

Also, in case you want to remove your previous rectangle before drawing the new one, you will need to:

  1. Define your canvas context (ctx) outside your rectangle function, so you can access it inside randomMove directly

  2. Define this bit just before calling your rectangle function to clear the previous drawing:

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

1 Comment

Did you meant setTimeout instead of setInterval?

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.