随机色值
一、RGB 随机色值
思路: 实现 RGB
随机色值的思路是分别生成红、绿、蓝三个通道的随机整数(范围均为 0 ~ 255
),然后拼接成 rgb(r, g, b)
的字符串格式。说明: Math.random()
生成 [0,1)
之间的随机小数, Math.floor(Math.random() * 256)
将随机小数乘以 256
,再向下取整,得到 0
到 255
的整数。
function randomRGBColor() {
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
return `rgb(${r}, ${g}, ${b})`;
}
console.log(randomRGBColor());
二、十六进制随机色值
思路: 使用 Math.random()
生成一个 [0, 1)
之间的随机小数,然后乘以 0xFFFFFF
(即 16777215
),通过 Math.floor()
取整, 得到一个介于 000000
和 ffffff => 16777215
之间的整数。通过 toString(16)
方法将整数转换为 16
进制字符串。使用 padStart(6, '0')
方法确保生成的字符串长度为 6
位,如果不足则在前面补 0
。
function randomHexColor() {
const randomInt = Math.floor(Math.random() * 0xffffff);
const colorStr = randomInt.toString(16).padStart(6, "0");
return `#${colorStr}`;
}
console.log(randomHexColor());