Created
April 4, 2024 14:12
-
-
Save nachodd/9b13cb1c644416df709f7a801a951efd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Converts a hex color code to an RGB color object. | |
* @param {string} hex - The hex color code to convert. | |
* @returns {object} An object with the red, green, and blue components of the RGB color. | |
*/ | |
function hexToRGB(hex) { | |
// Remove the # character from the beginning of the hex code | |
hex = hex.replace("#", ""); | |
// Convert the red, green, and blue components from hex to decimal | |
// you can substring instead of slice as well | |
const r = parseInt(hex.slice(0, 2), 16); | |
const g = parseInt(hex.slice(2, 4), 16); | |
const b = parseInt(hex.slice(4, 6), 16); | |
// Return the RGB value as an object with properties r, g, and b | |
return {r, g, b}; | |
} | |
/** | |
* Finds the color in the given array that is closest to the target color. | |
* @param {string} targetColor - The target color in hex string format (#RRGGBB). | |
* @param {string[]} colorArray - An array of colors to compare against the target color. | |
* @returns {string} The color in the array that is closest to the target color. | |
*/ | |
const closestColor = (targetColor, colorArray) => { | |
let closestDistance = 257; | |
let closestColor = null; | |
// Convert target color from hex string to RGB values | |
const {r: r1, g: g1, b: b1} = hexToRGB(targetColor); | |
// Loop through the array of colors | |
colorArray.forEach((color) => { | |
// Convert current color from hex string to RGB values | |
const {r: r2, g: g2, b: b2} = hexToRGB(color); | |
// Calculate the Euclidean distance between the target color and current color | |
const distance = Math.sqrt( | |
(r1 - r2) ** 2 + | |
(g1 - g2) ** 2 + | |
(b1 - b2) ** 2 | |
); | |
// Update closest color and distance if the current distance is smaller than the closest distance | |
console.log("distance", distance) | |
if (distance < closestDistance) { | |
closestDistance = distance; | |
closestColor = color; | |
} | |
}); | |
return closestColor; | |
} | |
// Usage: | |
const targetColor = "#f8d7da"; | |
const colorArray = ["#fff5f5", "#ffd0ce", "#ffaca7", "#ff8780", "#ff6259", "#ff3d32", "#d9342b", "#b32b23", "#8c221c", "#661814"]; | |
const closest = closestColor(targetColor, colorArray); | |
console.log(closest); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment