封装一个函数生成十六进制或者rgb颜色值

542 阅读1分钟

需求1

封装一个函数,为true时随机生成颜色的十六进制值或者为false时生成rgb值

分析:主要应用js内置对象Math,生成随机数,并且应用toString()转换成十六进制

     function getRandomColor(bool) {
             //生成十六进制
             if (bool) {
                 let str = ''
                 for (let i = 0; i < 6; i++) {
                     let a = Math.floor(Math.random() * 16).toString(16)
                     str += a
                 }
                 return `#${str}`
             }
             // 生成rgb值
             else {
                 let a = Math.floor(Math.random() * 256),
                     b = Math.floor(Math.random() * 256),
                     c = Math.floor(Math.random() * 256)
                 return `rgb(${a},${b},${c})`
             }
         }
         let res1 = getRandomColor(true)
         console.log(res1)
         let res2 = getRandomColor(false)
         console.log(res2)

需求2

封装一个函数,能够随机生成十六进制颜色值,要求内部逻辑用rbg值转换

思路分析:类似于需求1,先生成0-255随机数,注意Math,random函数是生成0-1随机数,但是出现0和1的几率几乎为0,所以生成0-225(包括0和255)要乘以256,然后向下取整

  function getColor16() {
             let arr = []
             for (let i = 0; i < 3; i++) {
                 // 生成0-255,包括0和255
                 arr[i] = Math.floor(Math.random() * 256)
                 // 这里是在转换成16进制之前就进行比较,小于16就采取补0的操作
                 if (arr[i] < 16) {
                     arr[i] = `0${arr[i].toString(16)}`
                 } else {
                     arr[i] = arr[i].toString(16)
                 }
                 arr[i] = arr < 16 ? `0${arr[i].toString(16)}` : arr[i].toString(16)
             }
             return `#${arr[0]}${arr[1]}${arr[2]}`
         }
         console.log(getColor16())