Skip to content

Instantly share code, notes, and snippets.

@maxwells
Created January 4, 2014 03:34
Show Gist options
  • Save maxwells/8251275 to your computer and use it in GitHub Desktop.
Save maxwells/8251275 to your computer and use it in GitHub Desktop.
Find the color between any two color points through linear interpolation. Pretty basic & straight forward. Progress bar demo at: http://jsfiddle.net/99ycK/1/
Color = function(hexOrObject) {
var obj;
if (hexOrObject instanceof Object) {
obj = hexOrObject;
} else {
obj = LinearColorInterpolator.convertHexToRgb(hexOrObject);
}
this.r = obj.r;
this.g = obj.g;
this.b = obj.b;
}
Color.prototype.asRgbCss = function() {
return "rgb("+this.r+", "+this.g+", "+this.b+")";
}
var LinearColorInterpolator = {
// convert 6-digit hex to rgb components;
// accepts with or without hash ("335577" or "#335577")
convertHexToRgb: function(hex) {
match = hex.replace(/#/,'').match(/.{1,2}/g);
return new Color({
r: parseInt(match[0], 16),
g: parseInt(match[1], 16),
b: parseInt(match[2], 16)
});
},
// left and right are colors that you're aiming to find
// a color between. Percentage (0-100) indicates the ratio
// of right to left. Higher percentage means more right,
// lower means more left.
findColorBetween: function(left, right, percentage) {
newColor = {};
components = ["r", "g", "b"];
for (var i = 0; i < components.length; i++) {
c = components[i];
newColor[c] = Math.round(left[c] + (right[c] - left[c]) * percentage / 100);
}
return new Color(newColor);
}
}
var l = new Color({ r:100, g:100, b:100 });
var r = new Color("#ffaa33");
var backgroundColor = LinearColorInterpolator.findColorBetween(l, r, 50).asRgbCss();
// do something with backgroundColor...
@lee101
Copy link

lee101 commented Oct 28, 2017

Awesome :)
just noting that this doesnt support colors like new Color("#FFF") (shorthand using only three wont set b channel).
also theres no clamping of percentages here e.g. can send 1million percent and it will go past the r color

@antoinerousseau
Copy link

@ems-ja
Copy link

ems-ja commented Nov 2, 2018

newColor[c] = Math.round(Math.sqrt((left[c]**2 + (right[c]**2 - left[c]**2) * percentage / 100));

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