Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get Random Color with Random Opacity (Useful for Charts)
const hexColors = [
'#3366CC',
'#DC3912',
'#FF9900',
'#109618',
'#990099',
'#3B3EAC',
'#0099C6',
'#DD4477',
'#66AA00',
'#B82E2E',
'#316395',
'#994499',
'#22AA99',
'#AAAA11',
'#6633CC',
'#E67300',
'#8B0707',
'#329262',
'#5574A6',
'#3B3EAC',
'#ff6384',
'#36a2eb',
'#ffce56',
]
export function getRandomColorWithRandomOpacity(shuffled = false, randomOpacity = false, minOpacity = 0.4, maxOpacity = 1) {
const colorArr = !shuffled ? [...hexColors] : suffledArray([...hexColors]);
return colorArr
.map(color =>
!randomOpacity
? hex2rgb(color)
: hex2rgb(color, getRandomOpacity(minOpacity, maxOpacity))
);
}
function getRandomOpacity(min = 0.4, maxOpacity = 1) {
return Math.min(Math.max(getRandomArbitrary(min - 0.1, maxOpacity + 0.1), min), maxOpacity);
}
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
// modified from https://stackoverflow.com/a/36048299/6120338
function hex2rgb(hex, opacity?) {
hex = hex.trim();
hex = hex[0] === '#' ? hex.substr(1) : hex;
const bigInt = parseInt(hex, 16);
const h = [];
if (hex.length === 3) {
h.push((bigInt >> 4) & 255);
h.push((bigInt >> 2) & 255);
} else {
h.push((bigInt >> 16) & 255);
h.push((bigInt >> 8) & 255);
}
h.push(bigInt & 255);
if (opacity) {
h.push(opacity);
}
return 'rgb(' + h.join() + ')';
}
// taken from https://stackoverflow.com/a/46545530/6120338
function suffledArray(arr = []) {
return arr
.map((a) => ({ sort: Math.random(), value: a }))
.sort((a, b) => a.sort - b.sort)
.map((a) => a.value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment