Skip to content

Instantly share code, notes, and snippets.

@krypton
Created April 16, 2012 17:22
Show Gist options
  • Save krypton/2400088 to your computer and use it in GitHub Desktop.
Save krypton/2400088 to your computer and use it in GitHub Desktop.
Calculate difference in percentage between 2 hex colors
function color_meter(cwith, ccolor) {
if (!cwith && !ccolor) return;
var _cwith = (cwith.charAt(0)=="#") ? cwith.substring(1,7) : cwith;
var _ccolor = (ccolor.charAt(0)=="#") ? ccolor.substring(1,7) : ccolor;
var _r = parseInt(_cwith.substring(0,2), 16);
var _g = parseInt(_cwith.substring(2,4), 16);
var _b = parseInt(_cwith.substring(4,6), 16);
var __r = parseInt(_ccolor.substring(0,2), 16);
var __g = parseInt(_ccolor.substring(2,4), 16);
var __b = parseInt(_ccolor.substring(4,6), 16);
var p1 = (_r / 255) * 100;
var p2 = (_g / 255) * 100;
var p3 = (_b / 255) * 100;
var perc1 = Math.round((p1 + p2 + p3) / 3);
var p1 = (__r / 255) * 100;
var p2 = (__g / 255) * 100;
var p3 = (__b / 255) * 100;
var perc2 = Math.round((p1 + p2 + p3) / 3);
return Math.abs(perc1 - perc2);
}
@gearsandcode
Copy link

Might as well live demo it, huh?
https://plnkr.co/edit/ERaf37?p=preview

@SmithersA
Copy link

Let's say that we found the percent difference between two blues to be 20 percent. Now we have a green color and we want it to be exactly the same percentage of difference (20 percent). Is there a way to rewrite the code/formula to find this?
Sort of like: x - y = 20%,
z +/- 20% = ?

@ashleedawg
Copy link

It's been a while since math class, but isn't is redundant to multiply both the numerator and the denominator by 100?

Also I'm curious if this method is documented somewhere as a standard method?

I don't see it listed on the Wikipedia page for Color Difference on the topic The easiest method shown there is the Euclidean colour difference formula:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment