js实现随机颜色
生成随机十六进制颜色
使用 Math.random() 和位运算生成六位十六进制颜色代码:
function getRandomHexColor() {
return `#${Math.floor(Math.random() * 0xFFFFFF).toString(16).padStart(6, '0')}`
}
生成RGB格式随机颜色
通过随机生成0-255之间的RGB分量值:

function getRandomRgbColor() {
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})`
}
生成HSL格式随机颜色
随机生成色相(0-360)和饱和度/明度(0-100%):

function getRandomHslColor() {
const h = Math.floor(Math.random() * 360)
const s = Math.floor(Math.random() * 100)
const l = Math.floor(Math.random() * 100)
return `hsl(${h}, ${s}%, ${l}%)`
}
带透明度的随机颜色
在RGB基础上增加alpha通道(0-1):
function getRandomRgbaColor() {
const r = Math.floor(Math.random() * 256)
const g = Math.floor(Math.random() * 256)
const b = Math.floor(Math.random() * 256)
const a = Math.random().toFixed(2)
return `rgba(${r}, ${g}, ${b}, ${a})`
}
颜色亮度控制
确保生成的颜色具有足够对比度(示例为亮色):
function getRandomLightColor() {
return `hsl(${Math.floor(Math.random() * 360)}, 100%, ${Math.floor(Math.random() * 30) + 70}%)`
}
所有方法都基于JavaScript的Math.random()函数实现,可以根据需要调整颜色范围或格式。十六进制方法中的padStart()确保颜色代码始终为6位,不足时补零。






