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

标签 javascript for-loop rgba

我对此很陌生,如果这是一个愚蠢的问题,我深表歉意。这只是一个简单的 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 + ")";

其中,rgb 是 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/

相关文章:

javascript - 使文本框中的默认值在使用 jQuery 输入文本之前不会更改

javascript - 过滤掉对象成员的好习惯用法(javascript)

javascript - 将对象数组转换为包含对象的数组的最佳方法

java - java和c中的for循环有什么区别吗?

c - C "for"循环出现问题 - 不会迭代过去的第一个

javascript - 谷歌图表和 JSON 数据

html - 仅在 Android 版 Chrome 中呈现的幻影元素——在检查时消失

c++ - CImg 库在旋转时创建扭曲的图像

c++ - Qt ( C++ ) 32 位 float 和 QRgba 之间的转换

javascript - 是否可以从本地主机加载一个特定文件?