生成随机颜色

51 阅读1分钟

颜色的格式有好几种rgb hex 等 在浏览器上颜色是16进制来表示

先来写个rgb格式的

function getRandomColor(){
    const num1 = Math.floor(Math.random()*256)
    const num2 = Math.floor(Math.random()*256)
    const num3 = Math.floor(Math.random()*256)
    const numArr = [num1,num2,num3]
    return `rgb(${numArr})`
}

再来写一个hex格式的

 function getRandom(){
    const s = Math.random().toString(16).slice(2,8)
    return '#'+s
 }

进阶版

 function getRandom(){
   const s = Math.floor(Math.random() * 0xffffff).toStirng(16).padStart(6,'0')
   return '#'+s
 }