在HTML5 Canvas中随机化RGB,使用Javascript为每个fillRect设置一个新值



我当前的代码随机化rgb,已经放在一个变量cr (color random)

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

我接着将变量放入fillstyle canvas元素中,以放置color:

ctx.fillStyle = cr;

过程中的fillRect按预期随机化。当前代码:

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()。例如:

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使用相同的随机颜色。我希望新的填充矩形有一个新的随机颜色(做一个很酷的天际线效果,所以可能还有20个或更多的这些)。也许,我需要在数组中放入一个循环,随机化它,并为每个新的fillRect使用。

回答晚了,但只是使用HSL:

设置随机颜色样式
ctx.fillStyle = 'hsl(' + 360 * Math.random() + ', 50%, 50%)';

这将创建一个具有相同饱和度和光强度(亮度)的随机颜色

我不知道你想以什么顺序画多少个矩形,但是你想把它放入函数中并运行几次。

下面是您可能想要查看的代码,以便使用您的代码简单地生成正方形:

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();

,这段代码将生成疯狂的矩形。

使用这里提供的函数

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.rect(20, 10, 200, 100);
context.fillStyle = getRandomColor();
context.fill();
演示JSFiddle

最新更新