Skip to content

Instantly share code, notes, and snippets.

@HanSolo
Created June 5, 2012 11:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HanSolo/2874530 to your computer and use it in GitHub Desktop.
Save HanSolo/2874530 to your computer and use it in GitHub Desktop.
Get rgb values of a color, convert them to hsl values and adjust the lightness of the color
var color = 'rgb(10, 24, 180)';
var rgb = getRgbValues(color);
var red = rgb[0];
var green = rgb[1];
var blue = rgb[2];
var hsl = rgb2Hsl(red, green ,blue);
var hue = hsl[0];
var saturation = hsl[1];
var lightness = hsl[2];
var newColor = 'hsl(' + hue + ', ' + saturation + '%, 40%)';
// Color lookup buffer
var lookupBuffer = doc.createElement('canvas');
lookupBuffer.width = 1;
lookupBuffer.height = 1;
var lookupCtx = lookupBuffer.getContext('2d');
var getRgbValues = function(color) {
lookupCtx.beginPath();
lookupCtx.rect(0, 0, 1, 1);
lookupCtx.fillStyle = color;
lookupCtx.fill();
var rgbData = lookupCtx.getImageData(0, 0, 1, 1).data;
lookupCtx.clearRect(0, 0, 1, 1);
return new Array(rgbData[0], rgbData[1], rgbData[2]);
};
var rgb2Hsl = function(red, green, blue) {
red /= 255;
green /= 255;
blue /= 255;
var max = Math.max(red, green, blue);
var min = Math.min(red, green, blue);
var hue;
var saturation;
var lightness = (max + min) / 2;
if (max == min) {
hue = saturation = 0; // achromatic
} else {
var delta = max - min;
saturation = lightness > 0.5 ? delta / (2 - max - min) : delta / (max + min);
switch (max) {
case red:
hue = (green - blue) / delta + (green < blue ? 6 : 0);
break;
case green:
hue = (blue - red) / delta + 2;
break;
case blue:
hue = (red - green) / delta + 4;
break;
}
hue /= 6;
}
return [(hue * 360), (saturation * 100), (lightness * 100)];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment