Calculate the distance between two colors in p5.js

16 August 2020


In building Wayfinder I needed to calculate the distance between two colors in order to find the closest color match.

The function takes two color object as inputs, and gives a number between 0 and 765, where a lower number indicates a closer match.

let black = color('#000');
let white = color('#fff');

let distance = colorDistance(black, white);

function colorDistance(first, second) {

    let r = abs(red(first) - red(second));
    let g = abs(green(first) - green(second));
    let b = abs(blue(first) - blue(second));

    return r + g + b;
}

abs() gives the absolute value of a number; turning any negative numbers into positives.

I like working with awesome people on awesome projects.
Let me know what you’re working on. Drop me a line at