您需要检查颜色的亮度,然后进行相应的调整
const randomColors = persons.map(() => {
let color = `#${Math.floor(Math.random() * 16777215).toString(16)}`;
while (isLight(color)) { //check if color is dark enough
color = `#${Math.floor(Math.random() * 16777215).toString(16)}`;
}
return color;
});
return randomColors;
}, [persons]);
function isLight(color) {
const hex = color.replace('#', '');
const r = parseInt(hex.substr(0, 2), 16);
const g = parseInt(hex.substr(2, 2), 16);
const b = parseInt(hex.substr(4, 2), 16);
//calculate luminance
const luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b;
return luminance > 150;
}