Color difference/similarity% between two values with JS

I need to compute the difference between two hex color values so the output is a percentage value. The first thing I discarted was converting the hex value into decimal, as the first one will have much higher weight than the last.

The second option is to compute the difference between each of the RGB values and then add them all. However, the difference between 0, 0, 0 and 30, 30, 30 is much lower than the one between 0, 0, 0 and 90, 0, 0.

This question recommends using YUV, but I can’t figure out how to use it to establish the difference.

Also, this other question has a nice formula to compute the difference and output a RGB value, but it’s not quite there.


Just compute an Euclidean distance:

var c1 = [0, 0, 0],
    c2 = [30, 30, 30],
    c3 = [90, 0, 0],
    distance = function(v1, v2){
        var i,
            d = 0;

        for (i = 0; i < v1.length; i++) {
            d += (v1[i] - v2[i])*(v1[i] - v2[i]);
        return Math.sqrt(d);

console.log( distance(c1, c2), distance(c1, c3), distance(c2, c3) );
//will give you 51.96152422706632 90 73.48469228349535

Leave a Reply

Your email address will not be published. Required fields are marked *