Published
Edited
Sep 29, 2022
Importers
6 stars
Insert cell
Insert cell
Insert cell
Insert cell
getRandomPalette = (opts) => {
const {
bgLightness,
length,
maxAttempts,
minColorDifference,
background,
minContrast
} = Object.assign(
{
length: 3, // Number of colors to be generated (excluding background)
background: undefined, // Background based which contrasting colors are generated.
bgLightness: undefined, // Background lightness. Range: [0.0-1.0]. Only used in case a backgroud color is not provided.
maxAttempts: 100, // Max number of attempts to generate given numbers
minColorDifference: 20, // Minimum color difference between other colors. Refer: https://culorijs.org/api/#differenceCie76
minContrast: 1.5 // Minimum contrast ratio for a generated color with background
},
opts
);
let bg = background || getRandomColor(bgLightness);

let iter = 0;
const colors = [];

while (iter < maxAttempts && colors.length < length) {
const nextColor = getRandomContrastColor(bg, minContrast);

const similarColor = colors.find(
(pickedColor) =>
colorDifference(pickedColor, nextColor) < minColorDifference
);

if (!similarColor) {
colors.push(nextColor);
}
iter++;
}

return {
background: bg,
colors
};
}
Insert cell
colorDifference = (color1, color2) => {
return culori.differenceCie76()(culori.parse(color1), culori.parse(color2));
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more