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

4

我当前用于随机化rgb的代码已经放在了变量cr(颜色随机)中。

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

我把变量放在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中使用。任何解决方案都将不胜感激 :)
3个回答

6
晚了一点回答,但只需使用HSL设置随机颜色样式即可:
ctx.fillStyle = 'hsl(' + 360 * Math.random() + ', 50%, 50%)';

这将创建一个随机颜色,其饱和度和亮度(光度)相同。

2

我不知道你想要画多少个矩形,以及它们的顺序,但你可以将这个过程放入一个函数中并运行多次。

下面是你可能想要查看的代码,它可以使用你的代码不断生成正方形:

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

这段代码将会生成许多矩形。


修改了问题。非常感谢您的反馈,这仍然是很酷的 :) - Charlie-Greenman
每次你想要创建一个新的颜色时,你都必须再次声明 cr, 这就是为什么我将 var cr = 'rgb('+......' 放在函数内部,这样每次绘图时,你都会得到新的颜色。 - milez770

0

使用此处提供的函数

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');

context.rect(20, 10, 200, 100);
context.fillStyle = getRandomColor();
context.fill();

演示 JSFiddle


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接