数据处理 | 颜色生成(16进制 or rgb)

需求1

封装一个函数,用于生成颜色(16进制或者rgba)

传入boolean为true时随机生成颜色的十六进制值,传入false时生成rgba值

需求2

封装一个函数,能够随机生成16进制颜色值,要求使用内部rag值的转换

十六进制颜色特点

0-9 A-F组成(字母不区分大小写)

rgb颜色特点

rgb包含三个参数,分别代表红色、绿色、蓝色

三个参数取值为0-255或者是0%-100%

实现思路

利用Math.random()生成随机数进行取值

实现1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function getRandomColor(bool) {
// 生成十六进制
if (bool) {
let str = '';
for (let i = 0; i < 6; i++) {
// Math.random() 取值为0-1 toString(16)转为16进制
let c = Math.floor(Math.random()*16.toString(16));
str += c;
};
return `#${str}`
} else { // 生成rgba值
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})`;
}
}

实现2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function getColor16() {
let arr = [];
for (let i = 0; i < 3; i++) {
// 生成r/g/b
arr[i] = Math.floor(Math.random()*256);

// 16进制转换
arr[i] = arr[i] < 16 ? `0${arr[i].toString(16)}` : arr[i].toString(16);
}
return '#' + arr.join('');
}

// test
console.log(getColor16()); // #6861b8