How to print random number of times one drawing in canvas javascript?

I have a canvas and I draw a rectangle in one function, in a new function I need to print this square a random number of times between 5 and 10.

I know I have to use Math.floor(Math.random() * 5) + 5 but now what I need to do to print the rectangle randomly 5 or 10 times.

This is what I’ve got so far, but not sure how to make it work

function rectangle() {
  ctx.beginPath();
  ctx.rect(20, 20, 150, 100);
  ctx.stroke();
}

function randomRect(){
  Math.floor(Math.random() * 5) + 5;
  rectangle()
}

Answer

You can use Math.random as a parameter inside a for loop.

const ctx = document.querySelector('canvas').getContext('2d');

function rectangle(x, y) {
  ctx.beginPath();
  ctx.rect(x, y, 50, 50);
  ctx.stroke();
}

function randomRect() {
  const squareCount = Math.floor(Math.random() * 5) + 5;
  for (var i = 0; i < squareCount; i++) {
    // Stagger the x,y position so the squares aren't on top of each other
    rectangle(i * 10, i * 10);
  };
};

randomRect()
canvas {
  width: 400px;
  height: 400px;
  border: 1px dashed firebrick;
}
<canvas></canvas>

Leave a Reply

Your email address will not be published. Required fields are marked *