封装随机颜色函数

570 阅读1分钟

封装随机rgb颜色的函数

  • Math.random()取随机数
  • 封装补零函数
  • 模板字符串拼接
// ◆封装一个随机rgb颜色的函数
function rgbColor() {
    let r = padZero(parseInt(Math.random() * 256))
    let g = padZero(parseInt(Math.random() * 256))
    let b = padZero(parseInt(Math.random() * 256))
    return `rgb(${r},${g},${b})`
}
// ◆封装补零函数
function padZero(num) {
    return num < 100 ? '0' + num : num
}
// ◆调用函数,并打印结果查看
console.log(rgbColor())

image.png

封装随机十六进制颜色的函数

  • for 循环
  • 十进制转十六进制 toString(16)
  • 取数组 随机下标
// ◆封装随机十六进制颜色1
function strColor1() {
    const arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
    let str = '#'
    for (let i = 0; i < 6; i++) {
        let sub = parseInt(Math.random() * 16)
        str += arr[sub]
    };
    return str
}
// ◆封装随机十六进制颜色2
function strColor2() {
    let str = "#"
    for (let i = 0; i < 6; i++) {
        str += parseInt(Math.random() * 16).toString(16)
    }
    return str
}
// ◆调用两函数,并打印结果查看
console.log(strColor1(), strColor2())

image.png