Skip to content

Instantly share code, notes, and snippets.

@sheminanto
Last active November 24, 2022 10:20
Show Gist options
  • Save sheminanto/36fabc67273f3d019917895a65dffa53 to your computer and use it in GitHub Desktop.
Save sheminanto/36fabc67273f3d019917895a65dffa53 to your computer and use it in GitHub Desktop.
To find the most similar base colour for any random colour (Javascript)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body>
<div id="palette" class="flex space-x-2"></div>
<script>
const colors = [
"#ffffff",
"#f5d3d4",
"#faddcc",
"#f3e4ac",
"#c8e2ba",
"#c2e6e0",
"#d2e1ec",
"#e0cee5",
];
const hexToHSL = (H) => {
// Convert hex to RGB first
let r = 0,
g = 0,
b = 0;
if (H.length === 4) {
r = "0x" + H[1] + H[1];
g = "0x" + H[2] + H[2];
b = "0x" + H[3] + H[3];
} else if (H.length === 7) {
r = "0x" + H[1] + H[2];
g = "0x" + H[3] + H[4];
b = "0x" + H[5] + H[6];
}
// Then to HSL
r /= 255;
g /= 255;
b /= 255;
let cmin = Math.min(r, g, b),
cmax = Math.max(r, g, b),
delta = cmax - cmin,
h = 0,
s = 0,
l = 0;
if (delta === 0) h = 0;
else if (cmax === r) h = ((g - b) / delta) % 6;
else if (cmax === g) h = (b - r) / delta + 2;
else h = (r - g) / delta + 4;
h = Math.round(h * 60);
if (h < 0) h += 360;
l = (cmax + cmin) / 2;
s = delta === 0 ? 0 : delta / (1 - Math.abs(2 * l - 1));
s = +(s * 100).toFixed(1);
l = +(l * 100).toFixed(1);
// return "hsl(" + h + "," + s + "%," + l + "%)";
return { hue: h, satutarion: s, lightness: l };
};
const paletteElement = document.getElementById("palette");
const colorToPredict = "#2fe6de";
const colorToPredictHSL = hexToHSL(colorToPredict);
const { index: predictedColorIndex } = colors.reduce(
(minimum, color, index) => {
const currentDifference = hexToHSL(color).hue - colorToPredictHSL.hue;
if (Math.abs(currentDifference) <= Math.abs(minimum.difference)) {
minimum.difference = currentDifference;
minimum.index = index;
}
return minimum;
},
{ difference: Number.MAX_VALUE, index: -1 }
);
colors.forEach((color, index) => {
const colorElement = document.createElement("div");
colorElement.className = "w-20 h-20";
colorElement.style.background = color;
if (index === predictedColorIndex) {
colorElement.classList.add("border-4");
colorElement.classList.add("border-sky-500");
}
paletteElement.appendChild(colorElement);
});
const colorElement = document.createElement("div");
colorElement.className = "w-32 h-32";
colorElement.style.background = colorToPredict;
paletteElement.appendChild(colorElement);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment