Reputation: 37
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
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
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:
Define your canvas context (ctx) outside your rectangle
function, so you can access it inside randomMove
directly
Define this bit just before calling your rectangle
function to clear the previous drawing:
ctx.clearRect(0, 0, canvas.width, canvas.height);
Upvotes: 0