Skip to content

Instantly share code, notes, and snippets.

@clok
Created April 29, 2012 14:38
Show Gist options
  • Select an option

  • Save clok/2550858 to your computer and use it in GitHub Desktop.

Select an option

Save clok/2550858 to your computer and use it in GitHub Desktop.
Hex Color Fade Picker Plugin for ImpactJS
ig.module(
'plugins.color-picker'
)
.requires(
)
.defines(function(){
// Initialize object with a default 10 color array fading from
// Green to Red
ColorPicker = function(){
// Generate default Colors Array with Red to Green in 10 steps
this.colors = this.genHexArray( 0x00FF00, 0xFF0000, 10 );
return(this);
}
// Select a color between color 1 (hc1) and color 2 (hc2)
// based on an input ratio that denotes the point in the
// gradient color should be selected from
ColorPicker.prototype.pickHex = function( hc1, hc2, ratio ){
if (ratio > 1) ratio = 1;
var r = hc1 >> 16;
var g = hc1 >> 8 & 0xFF;
var b = hc1 & 0xFF;
var r2 = hc2 >> 16;
var g2 = hc2 >> 8 & 0xFF;
var b2 = hc2 & 0xFF;
r += (r2 - r) * ratio;
g += (g2 - g) * ratio;
b += (b2 - b) * ratio;
var rethCol = (r<<16 | g<<8 | b).toString(16);
// Check that the converted hex string is properly "0" front loaded
while (rethCol.length < 6) {
rethCol = '0' + rethCol;
}
return(rethCol);
}
// Select n=steps colors between color 1 (hc1) and color 2 (hc2)
// and populate a return array
ColorPicker.prototype.genHexArray = function( hc1, hc2, steps ){
var r = hc1 >> 16;
var g = hc1 >> 8 & 0xFF;
var b = hc1 & 0xFF;
var r2 = hc2 >> 16;
var g2 = hc2 >> 8 & 0xFF;
var b2 = hc2 & 0xFF;
var colorArray = [];
colorArray[0] = hc1.toString(16);
for (var i = 1; i < steps; i++){
r += (r2 - r) * i/(steps-1);
g += (g2 - g) * i/(steps-1);
b += (b2 - b) * i/(steps-1);
colorArray[i] = (r<<16 | g<<8 | b).toString(16);
}
// Check that the converted hex strings are properly "0" front loaded
for (var j = 0; j < colorArray.length; j++){
while (colorArray[j].length < 6) {
colorArray[j] = '0' + colorArray[j];
}
}
return(colorArray);
}
ColorPicker.prototype.frontPad = function ( hex ) {
while (hex.length < 6) {
hex = '0' + hex;
}
return hex;
}
});
@clok
Copy link
Author

clok commented May 2, 2012

Consider improving performance by using "new Array()". See http://jsperf.com/arraynew/2

@clok
Copy link
Author

clok commented May 13, 2012

This Gist has migrated to the impactjs-color-picker redo. https://github.com/clok/impactjs-color-picker

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