Skip to content

Instantly share code, notes, and snippets.

@mailtruck
Forked from krypton/colormeter.js
Created April 18, 2012 07:09
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save mailtruck/2411659 to your computer and use it in GitHub Desktop.
Save mailtruck/2411659 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);
}
@tillsanders
Copy link

Works fine :) Thx.

@devnix
Copy link

devnix commented Sep 23, 2016

if (!cwith && !ccolor) return;

Would be this better?

if (!cwith || !ccolor) return;

Or even maybe

if (!cwith || !ccolor) return false;

@devnix
Copy link

devnix commented Sep 23, 2016

@rautamiekka
Copy link

When running this script on http://js.do this line is given:

JavaScript error: TypeError: cwith.charAt is not a function on line 9

You can see the used code in http://js.do/code/color_meter-test-0

@rautamiekka
Copy link

@gearsandcode
Copy link

@rautamiekka - it needs to be a string.

color_meter('#6D161C','#E45E69');

@Shuunen
Copy link

Shuunen commented Sep 8, 2017

works great 👍 thanks !!

@trickeyone
Copy link

I know this is really old, but I found it helpful. Put this into a plunkr to make it easier to test out in practice, if needed.

https://plnkr.co/edit/Yi9mApupEbA6dbml?p=preview

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