Skip to content

Instantly share code, notes, and snippets.

@derrickwilliams
Created January 18, 2018 14:11
Show Gist options
  • Select an option

  • Save derrickwilliams/43d1f6451bd78ef99ce46a0be8cadacd to your computer and use it in GitHub Desktop.

Select an option

Save derrickwilliams/43d1f6451bd78ef99ce46a0be8cadacd to your computer and use it in GitHub Desktop.
var colorHelper = {
// only accepts hex values for now
transitionSteps: function(colors, numberOfSteps) {
var _this = this;
var fromColor = _this.hexToRGB(colors.from);
var toColor = _this.hexToRGB(colors.to);
var diff = rgbDiff(fromColor, toColor);
var steps = breakIntoSteps(diff, numberOfSteps);
return getTransitions(fromColor, toColor, diff, steps, numberOfSteps);
function rgbDiff(rgb1, rgb2) {
return [
rgb2[0] - rgb1[0],
rgb2[1] - rgb1[1],
rgb2[2] - rgb1[2]
];
}
function breakIntoSteps(diff, numberPerStep) {
var steps = [];
for (var i = 0; i < diff.length; i++) {
steps[i] = Math.abs(diff[i] / numberPerStep);
}
return steps;
}
function getTransitions(rgb1, rgb2, diff, stepIncrements, steps) {
var rgbs = [];
for (var i = 0; i < steps; i++) {
var temp = [];
var nextR = (diff[0] >= 0) ? (rgb1[0] + stepIncrements[0] * i) : (rgb1[0] - stepIncrements[0] * i);
var nextG = (diff[1] >= 0) ? (rgb1[1] + stepIncrements[1] * i) : (rgb1[1] - stepIncrements[1] * i);
var nextB = (diff[2] >= 0) ? (rgb1[2] + stepIncrements[2] * i) : (rgb1[2] - stepIncrements[2] * i);
rgbs.push([
nextR > 255 ? 255 : parseInt(nextR, 10),
nextG > 255 ? 255 : parseInt(nextG, 10),
nextB > 255 ? 255 : parseInt(nextB, 10)
]);
}
rgbs.push([
rgb1[0] + diff[0],
rgb1[1] + diff[1],
rgb1[2] + diff[2]
]);
return rgbs;
}
},
hexToRGB: function(hex) {
return [ hexToR(hex), hexToG(hex), hexToB(hex) ];
function hexToR(h) {return parseInt((cutHex(h)).substring(0,2),16);}
function hexToG(h) {return parseInt((cutHex(h)).substring(2,4),16);}
function hexToB(h) {return parseInt((cutHex(h)).substring(4,6),16);}
function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h;}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment