使用Javascript为每个fillRect使用新值在HTML5画布中随机化RGB

使用Javascript为每个fillRect使用新值在HTML5画布中随机化RGB,javascript,canvas,random,html5-canvas,Javascript,Canvas,Random,Html5 Canvas,我当前用于随机rgb的代码,已放入变量cr(颜色随机) 我继续将变量放入fillstyle画布元素以放置颜色: ctx.fillStyle = cr; 正在进行的fillRect按预期随机化。当前代码: var c = document.getElementById('canvas'); var ctx = c.getContext('2d'); var cr = 'rgb('+ Math.floor(Math.random()*256)+','+ Math.floo

我当前用于随机rgb的代码,已放入变量cr(颜色随机)

我继续将变量放入fillstyle画布元素以放置颜色:

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使用相同的随机颜色。我希望新的fillRect有一个新的随机颜色(做一个很酷的天际线效果,所以可能还有20个或更多)。也许,我需要将一个循环放入一个数组中,随机化它,并用于每个新的fillRect。任何解决方案都将不胜感激:)

我不知道您希望以什么顺序绘制多少个矩形,但您希望将其放入函数并运行几次

以下是您可能希望查看的代码,以便继续使用您的代码生成正方形:

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

这段代码将生成矩形

使用中提供的功能


延迟回答,但只需使用HSL设置随机颜色样式:

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

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

编辑问题。非常感谢您的输入,这仍然很酷:)每次您想要创建新颜色时,您都必须声明cr Again这就是为什么我在函数中放置var cr='rgb('+..),因此每次您绘制时,您都可以获得新颜色
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');

context.rect(20, 10, 200, 100);
context.fillStyle = getRandomColor();
context.fill();
ctx.fillStyle = 'hsl(' + 360 * Math.random() + ', 50%, 50%)';