JS——JS随机生成颜色

16进制颜色(#000000-#FFFFFF)

/**
 * 随机生成16进制颜色
 * @returns 
 */
const randomHexColor = function () {
    var hex = Math.floor(Math.random() * 16777216).toString(16); //生成ffffff以内16进制数
    while (hex.length < 6) { //while循环判断hex位数,少于6位前面加0凑够6位
        hex = '0' + hex;
    }
    return '#' + hex; //返回‘#’开头16进制颜色
}

RGB格式颜色(rgb(r,g,b))

/**
 * 随机生成RGB颜色
 * @returns 
 */
const randomRgbColor = function () {
    var r = Math.floor(Math.random() * 256); //随机生成256以内r值
    var g = Math.floor(Math.random() * 256); //随机生成256以内g值
    var b = Math.floor(Math.random() * 256); //随机生成256以内b值
    return `rgb(${r},${g},${b})`; //返回rgb(r,g,b)格式颜色
}

 

posted @ 2022-06-22 14:26  话·醉月  阅读(1494)  评论(0编辑  收藏  举报