尝试创建一页正方形,每个正方形都有不同的颜色。到目前为止,我有一个可以工作的随机颜色生成器,但到目前为止,它每次加载页面时都会将每个方 block 设置为相同的随机颜色,只是试图找出一种方法来为每个方 block 提供不同的随机颜色。
我尝试过使用函数来创建不同的颜色,但效果不太好,这是我的随机数生成器的代码:
var red = Math.floor(Math.random()* 255);
var green = Math.floor(Math.random() * 255);
var blue = Math.floor(Math.random() * 255);
这是我的一个方 block 的代码(所有方 block 都有相同的代码,只是坐标不同)
ctx.rect(820, 50,100,100);
ctx.closePath();
ctx.fillStyle = "rgb("+red+","+green+"," +blue+" )";
ctx.fill();
完整代码在这里:
<html>
<canvas id="canvas1" height="768" width="1024" style="border: 1px solid #000000;"></canvas>
<script>
var canvas = document.getElementById("canvas1");
var ctx = canvas.getContext("2d");
var red = Math.floor(Math.random() * 255);
var green = Math.floor(Math.random() * 255);
var blue = Math.floor(Math.random() * 255);
ctx.beginPath();
ctx.rect(70, 50, 100, 100);
ctx.closePath();
ctx.fillStyle = "rgb(" + red + "," + green + "," + blue + " )";
ctx.fill();
ctx.rect(220, 50, 100, 100);
ctx.closePath();
ctx.fillStyle = "rgb(" + red + "," + green + "," + blue + " )";
ctx.fill();
ctx.rect(370, 50, 100, 100);
ctx.closePath();
ctx.fillStyle = "rgb(" + red + "," + green + "," + blue + " )";
ctx.fill();
ctx.rect(520, 50, 100, 100);
ctx.closePath();
ctx.fillStyle = "rgb(" + red + "," + green + "," + blue + " )";
ctx.fill();
ctx.rect(670, 50, 100, 100);
ctx.closePath();
ctx.fillStyle = "rgb(" + red + "," + green + "," + blue + " )";
ctx.fill();
ctx.rect(820, 50, 100, 100);
ctx.closePath();
ctx.fillStyle = "rgb(" + red + "," + green + "," + blue + " )";
ctx.fill();
</script>
</html>
最佳答案
这只会在绘制矩形之前设置一次颜色;
var red = Math.floor(Math.random()* 256);
var green = Math.floor(Math.random() * 256);
var blue = Math.floor(Math.random() * 256);
您可以创建一个函数来执行此操作并返回值;
function getRandomColour(){
var red = Math.floor(Math.random() * 256);
var green = Math.floor(Math.random() * 256);
var blue = Math.floor(Math.random() * 256);
return "rgb("+red+","+green+"," +blue+" )";
}
或者,您可以在数组中预先定义矩形值并循环它们以绘制矩形。代码会更少。
var canvas = document.getElementById("canvas1");
var ctx = canvas.getContext("2d");
function getRandomColour(){
var red = Math.floor(Math.random() * 256);
var green = Math.floor(Math.random() * 256);
var blue = Math.floor(Math.random() * 256);
return "rgb("+red+","+green+"," +blue+" )";
}
ctx.fillStyle = getRandomColour();
ctx.fillRect(70,50,100,100);
ctx.fillStyle = getRandomColour();
ctx.fillRect(10,10,100,100);
<canvas id="canvas1"></canvas>
关于javascript - 为 HTML5 Canvas 上的每个形状赋予随机颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50528954/