DEV Community

Cover image for Find closest RGB component from a color
Manish Gopal Singh
Manish Gopal Singh

Posted on • Updated on

Find closest RGB component from a color

Recently I was asked to find the closest RGB component (red or green or blue) from a color. I had no clue at that time. Later I Googleed and found out there is a formula to calculate the distance between two colors.

This is the formula I found on wiki
distance formula

Let's say we have two colors, rgb(0,206,102) and rgb(118,184,225). If we assume rgb(0,206,102) to (x1,y1,z1) and rgb(118,184,225) to (x2,y2,z2). We can draw two points (0,206,102) and (118,184,225) on a three dimensional co-ordinate graph.

Three dimension co-ordinate graph

We can calculate the distance between two points as follows


let distance = Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)+(z1-z2)*(z1-z2))
distance = Math.sqrt((0-118)*(0-118)+(206-184)*(206-184)+(102-225)*(102-225))
distance = 171.86331778480246

Enter fullscreen mode Exit fullscreen mode

Now, let's solve the current problem.

Create a function which will find the distance between two colors.


const distanceBetweenTwoColors = (color1, color2) => {
        const [r1,g1,b1] = color1;
        const [r2,g2,b2] = color2;
        return (r1-r2) * (r1-r2) + (g1-g2) * (g1-g2) + (b1-b2) * (b1-b2);
    };

Enter fullscreen mode Exit fullscreen mode

If you notice the function, we skip Math.sqrt because we are required to do comparison between values instead of absolute computation of a value.

Create a list of colors so that we can compare the distance between given color to our list.


const colorList = {'black':[0,0,0], 'white':[255,255,255], 'red':[255,0,0], 'green': [0,255,0], 'blue':[0,0,255]};

Enter fullscreen mode Exit fullscreen mode

Create a function which will loop through our colorlist and compare distance one by one with the given color and return to the closest one from the list.


const getClosestRGBComponentFromColor = (givenColor) => {
    let closestDistance = null;
    let closestColor = [];

    for (let color in colorList) {
        const distance = distanceBetweenTwoColors(colorList[color], givenColor);
        if (closestDistance === null || distance < closestDistance) {
            closestDistance = distance;
            closestColor = [color];
        } else if (closestDistance === distance) {
            closestColor.push(color);
        }
    }

  return closestColor;
}


Enter fullscreen mode Exit fullscreen mode

Now we can use it as shown below.


const color = [0,155,0];

console.log(`Closest to the  color "${getClosestRGBComponentFromColor(color)}"`);

// output: Closest to the color "green"


Enter fullscreen mode Exit fullscreen mode

Hope you find this article useful. Thank you for reading till the end.

Top comments (0)