Randomize RGB in HTML5 Canvas with a new value for each fillRect using Javascript
canvas, html5-canvas, javascript, random
Solution
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).
Problem
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 :)