4

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

Charlie-Greenman
  • 1,469
  • 1
  • 16
  • 36

3 Answers3

6

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

2

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.

milez770
  • 102
  • 8
  • Edited question. Really appreciate your input, and this is still pretty cool :) – Charlie-Greenman May 26 '14 at 01:33
  • everytime you want to make new color you have to declare cr agiain this is why i put var cr = 'rgb('+...... within the function so everytime you draw, you get new color – milez770 May 26 '14 at 01:41
0

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

Community
  • 1
  • 1
jhyap
  • 3,779
  • 6
  • 27
  • 47