Charlie-Greenman
Charlie-Greenman

Reputation: 1659

Randomize RGB in HTML5 Canvas with a new value for each fillRect using Javascript

My current code for randomizing rgb, has been put in a variable cr (color random)

var cr = 'rgb('+
      Math.floor(Math.random()*256)+','+
      Math.floor(Math.random()*256)+','+
      Math.floor(Math.random()*256)+')';

I proceeded to put the variable in the fillstyle canvas element to place color:

ctx.fillStyle = cr;

The proceeding fillRect is randomized as expected. Current code:

var c = document.getElementById('canvas');
var ctx = c.getContext('2d');

var cr = 'rgb('+
      Math.floor(Math.random()*256)+','+
      Math.floor(Math.random()*256)+','+
      Math.floor(Math.random()*256)+')';

  ctx.fillStyle = cr;
  ctx.fillRect(0, 210 , 100 ,290);

The problem arises when I try to put it in a new fillRect(). For instance:

var c = document.getElementById('canvas');
var ctx = c.getContext('2d');

var cr = 'rgb('+
      Math.floor(Math.random()*256)+','+
      Math.floor(Math.random()*256)+','+
      Math.floor(Math.random()*256)+')';

  ctx.fillStyle = cr;
  ctx.fillRect(0, 210 , 100 ,290);

  ctx.fillStyle = cr;
  ctx.fillRect(100, 210, 100, 290);

The new ctx.fillStyle uses the same random color. I would like the new fillRect to have a new random color (doing a cool skyline effect so perhaps another 20 or more of these). Perhaps, I need to put a loop into an array, randomize it, and use for every new fillRect. Any solutions would be greatly appreciated :)

Upvotes: 4

Views: 11586

Answers (3)

user1693593
user1693593

Reputation:

Late answer, but just set the random color style using HSL:

ctx.fillStyle = 'hsl(' + 360 * Math.random() + ', 50%, 50%)';

This will create a random color with same saturation and light intensity (luminance).

Upvotes: 6

jhyap
jhyap

Reputation: 3837

Use the function provided in here

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');

context.rect(20, 10, 200, 100);
context.fillStyle = getRandomColor();
context.fill();

Demo JSFiddle

Upvotes: 0

milez770
milez770

Reputation: 112

I do not know how many rectangles in what order you want to draw but yes you would like to put this in to function and run it several times.

here is the code you might want to look at to simply keep generating squares using your code:

var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');

function rect(){
  var cr = 'rgb('+
    Math.floor(Math.random()*256)+','+
    Math.floor(Math.random()*256)+','+
    Math.floor(Math.random()*256)+')';

  ctx.fillStyle = cr;
  ctx.fillRect(Math.random()*50, Math.random()*50 , 50 ,50);

  requestAnimationFrame(rect);
}

rect();

and this code will generate rectangles crazy.

Upvotes: 2

Related Questions