Luna Rupert
Luna Rupert

Reputation: 37

How do I make a loop with a timer in canvas in javascript?

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
    }

Upvotes: 0

Views: 198

Answers (2)

Anastazy
Anastazy

Reputation: 4756

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>

Upvotes: 1

ale917k
ale917k

Reputation: 1768

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);

Upvotes: 0

Related Questions