1.采用Math.random()---安全性不高
export default function getRandomColor() {
let str = '#';
const arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
for (let i = 0; i < 6; i++) {
const num = parseInt(String(Math.random() * 16));
str += arr[num];
}
return str;
}
2.采用new Date()时间戳---数字重复较高,颜色比较单一
export default function getRandomColor() {
let str = '#';
const arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
for (let i = 0; i < 6; i++) {
const num = getRandomInt();
str += arr[num];
}
function getRandomInt() {
const timestamp = new Date().getTime();
const randomNum = timestamp % 16;
return randomNum;
}
return str;
}
3.Crypto API --- 使用的是浏览器内置的 Crypto API,随机性高安全性也高
我们将随机数与100取模,以得到介于0和99之间的数字。如果想生成0和15之间的数字,需要将随机数与16取模,但需要浏览器支持web Crypto API
export default function getRandomColor() {
let str = '#';
const arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
for (let i = 0; i < 6; i++) {
const cryptoArray = new Uint32Array(1);
window.crypto.getRandomValues(cryptoArray);
const randomValue = cryptoArray[0];
const num = randomValue % 16;
str += arr[num];
}
return str;
}