我对此很陌生,如果这是一个愚蠢的问题,我深表歉意。这只是一个简单的 for 循环来绘制 n 个圆圈,我想随机生成 rgba 值,但它采用最后使用的描边样式,我做错了什么?
for (var i = 0; i < 10; i++){
var x = Math.random() * window.innerWidth;
var y = Math.random() * window.innerHeight;
var colour = Math.random() * 255;
c.beginPath();
c.arc(x, y, 30, 0, Math.PI * 2, false);
c.strokeStyle = 'rgba(colour, colour, colour, Math.random())';
c.stroke(); }
非常感谢!!
最佳答案
这可以通过格式化颜色字符串来完成,如下所示:
"rgba(" + r + "," + g + "," + b + "," + a + ")";
其中,r
、g
、b
是 0 到 255 范围内的整数,a
是0.0 到 1.0 范围内的 float ;
有关完整示例,请参阅以下代码片段:
var c = document.getElementById("canvas").getContext("2d");
for (var i = 0; i < 10; i++) {
const x = Math.random() * c.canvas.width;
const y = Math.random() * c.canvas.height;
// Red, green, blue should be integers in the range of 0 - 255
const r = parseInt(Math.random() * 255);
const g = parseInt(Math.random() * 255);
const b = parseInt(Math.random() * 255);
// Alpha is a floating point in range of 0.0 - 1.0
const a = Math.random();
c.beginPath();
c.arc(x, y, 30, 0, Math.PI * 2, false);
c.strokeStyle = "rgba(" + r + "," + g + "," + b + "," + a + ")";
c.stroke();
}
<canvas id="canvas"></canvas>
或者,如果您的目标浏览器支持“模板文字”,则可以通过以下方式以更简洁的方式格式化相同的颜色字符串:
const r = parseInt(Math.random() * 255);
const g = parseInt(Math.random() * 255);
const b = parseInt(Math.random() * 255);
const a = Math.random();
// Format color string via template literal using back ticks ` and ${}
// to render scope variables to the string result
c.strokeStyle = `rgba(${r}, ${g}, ${b}, ${a})`;
关于Javascript 使用 Math.random 在 for 循环中生成随机 rgba 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53921589/