创建多色多边形,无需外部库或精灵

时间:2015-01-16 04:24:31

标签: javascript canvas

我试图创建一个9 x 9的矩形,我想让矩形的颜色排列变化。现在我使用fillStyle('#0000FF')用蓝色填充它,但我想用随机排列的颜色填充它。这可能吗?

2 个答案:

答案 0 :(得分:3)

这是一个生成半随机颜色的函数:

function randomColor(){ 
    return('#'+Math.floor(Math.random()*16777215).toString(16));
}

您可以为大矩形内的每个9x9子矩形执行context.fillStyle=randomColor()context.fillRect(...)

这是一个更好的示例代码和演示:



var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

ctx.lineWidth=10;
var nextTime=0;
var duration=1000;

requestAnimationFrame(animate);

function animate(time){
  requestAnimationFrame(animate);
  if(time>nextTime){
    nextTime=time+duration;
    ctx.clearRect(0,0,cw,ch);
    for(var i=0;i<cw*2;i+=ctx.lineWidth){
      ctx.beginPath();
      ctx.moveTo(i,-5);
      ctx.lineTo(i-cw,ch+5);
      ctx.strokeStyle=randomColor();
      ctx.stroke();
    }
  }
}

function randomColor(){ 
  return('#'+Math.floor(Math.random()*16777215).toString(16));
}
&#13;
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
&#13;
<canvas id="canvas" width=300 height=300></canvas>
&#13;
&#13;
&#13;

enter image description here

[更多提问者指出:-)]

&#13;
&#13;
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var colwidth=cw/9;
var rowheight=ch/9;

for(var y=0;y<9;y++){
for(var x=0;x<9;x++){
    ctx.fillStyle=randomColor();
    ctx.fillRect(x*colwidth,y*rowheight,colwidth,rowheight);
}}

function randomColor(){ 
  return('#'+Math.floor(Math.random()*16777215).toString(16));
}
&#13;
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
&#13;
<canvas id="canvas" width=300 height=300></canvas>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

要获得随机颜色,最好的方法是使用hsl系统(色调,饱和度,亮度) 通过这种方式,您可以轻松地塑造随机性&#39;的颜色。

下面的代码随机选择3种颜色方案中的一种,并使用此方案绘制矩形 使用hsl色轮找出适合的颜色。

&#13;
&#13;
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var colorScheme = -1;

function drawRect() {
  colorScheme = randInt(3);

  ctx.save();
  ctx.scale(30,30);
  var i=9,j;
  while(i--) {
     j=9;
     while(j--) {
       ctx.fillStyle=randomColor();
       ctx.fillRect(i,j,1, 1);
     }
  }
  ctx.restore();
}

drawRect();
setInterval(drawRect, 1400);
function randomColor(){ 
  var hue, saturation, lightness;
  // 8 bit : 6 very contrasted colors
  if (colorScheme == 0) {
     hue = 60*randInt(6);
     saturation = 85;
     lightness = 50;
  } 
  // random hue, normal sat/lgt
  if (colorScheme == 1) {
     hue = randInt(360);
     saturation = 80;
     lightness = 65;
  } 
  // red theme : all colors in 0-30, lightness in 65-100
  if (colorScheme == 2) {
     hue = randInt(30);
     saturation = 70;
     lightness = 65+randInt(36);
  } 
  
  return 'hsl(' + hue + ',' + saturation +  '%,' +lightness + '%)';
}

function randInt(max) {
   return Math.floor(Math.random()*max);  
}
&#13;
<canvas id="canvas" width=300 height=300></canvas>
&#13;
&#13;
&#13;