Javascript 使用 Math.random 在 for 循环中生成随机 rgba 值

Javascript Using Math.random to generate random rgba values in for loop

我对此很陌生,如果这是一个愚蠢的问题,我深表歉意。这只是一个简单的 for 循环,用于绘制 n 个圆圈,我想随机生成 rgba 值,但它使用了最后一个 strokeStyle,我做错了什么?

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(colour, colour, colour, Math.random())' 是一个文字字符串,这使它成为无效的 CSS(因为 CSS 无法识别 colourMath.random()),将被丢弃。

您可能需要 template literal(注意不同的引用):

c.strokeStyle = `rgba(${colour}, ${colour}, ${colour}, ${Math.random()})`

另外,请注意,这不会给你一个非常随机的颜色;它会给你一个随机的 灰色 颜色,因为你将 R、G 和 B 组件链接为相同 colour。如果希望三个分量能够不同,则需要为每个分量生成一个新的随机数。

这可以通过如下格式化颜色字符串来完成:

"rgba(" + r + "," + g + "," + b + "," + a + ")";

其中rgb为0~255范围内的整数,a为0.0~1.0范围内的浮点数;

有关完整示例,请参阅以下代码片段:

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>

或者,如果您的目标浏览器支持 "template literals",则可以通过以下方式以更简洁的方式格式化相同颜色的字符串:

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})`;