我正在尝试创建一个9 x 9的矩形,并希望使矩形的颜色排列多样化。现在我正在使用fillStyle('#0000FF')将其填充为蓝色,但我希望用随机排列的颜色来填充它。这是否可能?
我正在尝试创建一个9 x 9的矩形,并希望使矩形的颜色排列多样化。现在我正在使用fillStyle('#0000FF')将其填充为蓝色,但我希望用随机排列的颜色来填充它。这是否可能?
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));
}
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=300></canvas>
[ More to the questioners point :-) ]
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));
}
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=300></canvas>
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);
}
<canvas id="canvas" width=300 height=300></canvas>