Javascript-生成随机粘贴HEX/RGBA颜色



我有以下方法

export const generateRandomColor = () => {
const letters = "0123456789ABCDEF";
let color = "#";
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * letters.length)];
}
return color;
};

其产生随机颜色。我使用这个函数来获取饼图的颜色,当然,看到不同类型(浅色、深色、粉彩…(的颜色混合在一起一点也不优雅。

如何在JS(HEX或RGBA(中仅生成随机PASTEL颜色?

要生成一系列类似粉彩的颜色,您可以生成每个最小值为127:的通道

generatePastelColor = () => {
let R = Math.floor((Math.random() * 127) + 127);
let G = Math.floor((Math.random() * 127) + 127);
let B = Math.floor((Math.random() * 127) + 127);

let rgb = (R << 16) + (G << 8) + B;
return `#${rgb.toString(16)}`;      
}
document.querySelectorAll('#palette div').forEach( elem => {
elem.style.backgroundColor = generatePastelColor();
});
#palette {
width: 100px;
height: 100px;
}
#palette > div {
width: 100%;
height: 20px;
}
<div id="palette">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>

根据文档,React Native似乎支持hsl。如果这对你有用,那么这个答案可能会有所帮助。

最新更新