使用Javascript为HTML5 Canvas中的RGB随机化每个fillRect的新值 [英] Randomize RGB in HTML5 Canvas with a new value for each fillRect using Javascript
问题描述
我当前用于随机化rgb的代码已放入变量cr(颜色随机)
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)+')';
我继续将变量放在fillstyle画布元素中以放置颜色:
I proceeded to put the variable in the fillstyle canvas element to place color:
ctx.fillStyle = cr;
正在进行的fillRect按预期随机化。当前代码:
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);
当我尝试将其放入新的fillRect()时出现问题。例如:
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);
新的ctx.fillStyle使用相同的随机颜色。我希望新的fillRect有一个新的随机颜色(做一个很酷的天际线效果,所以可能还有20个或更多这些)。也许,我需要将一个循环放入一个数组中,随机化它,并用于每个新的fillRect。任何解决方案都将非常感激:)
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 :)
推荐答案
迟到的答案,但只需使用HSL设置随机颜色样式:
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).
这篇关于使用Javascript为HTML5 Canvas中的RGB随机化每个fillRect的新值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!