JS 生成颜色随机值的两种方式

1,174 阅读1分钟

第一种就是非常常见的方法:

生成 rgb 颜色值:利用 随机数 * 256 得到一个 0-255 的颜色值,然后向下取整

    function randomColor() {
        let r = Math.floor(Math.random() * 256)
        let g = Math.floor(Math.random() * 256)
        let b = Math.floor(Math.random() * 256)
        return `rgb(${r},${g},${b})`
    }

第二种方法:

生成 16 进制的颜色值:利用 Math.random().toString(16) 把数字转成 16 进制,然后取 6 位。

但是我们要注意,随机数可能是 0 ,0 转换不了 16 进制,所以我们需要判断一下然后递归。

    function randomColor() {
        let random = Math.random()
        if(random === 0) {
            return randomColor()
        }
        return '#' + random.toString(16).substring(2,8)
    }