Skip to content

Instantly share code, notes, and snippets.

@AbraaoAlves
Forked from alcidesqueiroz/colordiff
Last active December 17, 2015 20:09
Show Gist options
  • Save AbraaoAlves/5665512 to your computer and use it in GitHub Desktop.
Save AbraaoAlves/5665512 to your computer and use it in GitHub Desktop.
Percent Diff between two colors for RGB.
String.prototype.format = String.prototype.format || function(){
var format = this;
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (arg === null || arg === undefined) arg = "";
var regex = new RegExp("\\{" + i + "\\}", "g");
format = format.replace(regex, arg);
}
return format;
};
(function( exports ){
"use strict";
function colorHex( num1, num2, color ){
return parseInt(( color || "" ).substr( num1, num2 ), 16 );
}
var colorRed = colorHex.bind( this, 0, 2 );
var colorGreen = colorHex.bind( this, 2, 2 );
var colorBlue = colorHex.bind( this, 4, 2 );
var ColorDiff = (function(){
function ColorDiff( colorA, colorB ){this.colorA = colorA; this.colorB = colorB;}
ColorDiff.prototype.toString = function(){
return "{0}, $red: {1}%, $green: {2}%, $blue: {3}%".format(
this.colorA,
this._channelDifference( colorRed( this.colorA ), colorRed( this.colorB )),
this._channelDifference( colorGreen( this.colorA ), colorGreen( this.colorB )),
this._channelDifference( colorBlue( this.colorA ), colorBlue( this.colorB )));
};
ColorDiff.prototype.copySCSSInstruction = function(){
var instruction = "scale_color({0})".format(this.toString());
copy(instruction);
console.log(instruction);
};
ColorDiff.prototype._channelDifference = function ( colorA, colorB ){
var basis, diff, percent_diff = 0;
if(colorA > colorB){
basis = colorA;
diff = colorA - colorB;
percent_diff = -( diff / ( basis / 100 ));
}
if(colorA < colorB){
basis = 255 - colorA;
diff = colorB - colorA;
percent_diff = diff / ( basis / 100 );
}
return percent_diff.toFixed(2);
};
return ColorDiff;
}());
exports.ColorDiff = ColorDiff;
}(this));
var diff = new ColorDiff("95B8E7", "E6F1FD");
diff.toString()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment