Skip to content

Instantly share code, notes, and snippets.

@micheletolve
Created April 2, 2024 12:31
Show Gist options
  • Save micheletolve/7c68b680e0d0c5d8e985badf24af6aee to your computer and use it in GitHub Desktop.
Save micheletolve/7c68b680e0d0c5d8e985badf24af6aee to your computer and use it in GitHub Desktop.
/**
* Generate a random color in HEX format
* @param {number} opacity The opacity value between 0 and 1. If null use 1 as default value
* @param {number} whiteDistance distance from the white color. If null use 600 as default value
* @returns {string} the color in HEX format
* */
const generateRandomHexColor = (opacity, whiteDistance) => {
let r, g, b;
opacity ??= 1;
whiteDistance ??= 600;
do {
r = Math.floor(Math.random() * 256);
g = Math.floor(Math.random() * 256);
b = Math.floor(Math.random() * 256);
a = opacity;
} while (r + g + b > whiteDistance);
return `rgba(${r}, ${g}, ${b}, ${a})`;
}
/**
* Calculate the Euclidean distance between two colors https://it.wikipedia.org/wiki/Distanza_euclidea
* @param {any} color1
* @param {any} color2
* @returns {int} distance between two colors
*/
const colorDistance = (color1, color2) => {
const rDiff = color1.r - color2.r;
const gDiff = color1.g - color2.g;
const bDiff = color1.b - color2.b;
return Math.sqrt((rDiff * rDiff) + (gDiff * gDiff) + (bDiff * bDiff));
};
/**
* Generate an array of random color in HEX format
* @param {number} n number of colors to generate
* @param {number} opacity The opacity value between 0 and 1. If null use 1 as default value
* @param {number} whiteDistance distance from the white color. If null use 600 as default value
* @param {number} tooClose minumum distance between colors. If null use 100 as default value
* @returns {Array} array of colors in rgba
*/
const generateRandomArrayColor = (n, opacity, whiteDistance, tooClose) => {
opacity ??= 1;
whiteDistance ??= 600;
tooClose ??= 100;
const colors = [];
while (colors.length < n) {
const newColor = {
r: Math.floor(Math.random() * 256),
g: Math.floor(Math.random() * 256),
b: Math.floor(Math.random() * 256),
a: opacity
};
const tooClose = colors.some(existingColor => colorDistance(existingColor, newColor) < tooClose);
if (!tooClose && newColor.r + newColor.g + newColor.b <= whiteDistance) {
colors.push(newColor);
}
}
return colors.map(color => `rgba(${color.r}, ${color.g}, ${color.b}, ${color.a})`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment