Logo
Filmmaskiner.dk

hsl2hex: Convert hue, saturation, luminance color to HEX


The functions
function hslToRgb(h, s, l){
	var r, g, b;

	if(s == 0){
		r = g = b = l; // achromatic
	}else{
		var hue2rgb = function hue2rgb(p, q, t){
			if(t < 0) t += 1;
			if(t > 1) t -= 1;
			if(t < 1/6) return p + (q - p) * 6 * t;
			if(t < 1/2) return q;
			if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
			return p;
		}

		var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
		var p = 2 * l - q;
		r = hue2rgb(p, q, h + 1/3);
		g = hue2rgb(p, q, h);
		b = hue2rgb(p, q, h - 1/3);
	}
	return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
}

function componentToHex(c) {
	var hex = c.toString(16);
	return hex.length == 1 ? "0" + hex : hex;
}

function rgbToHex(r, g, b) {
	return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}

function hsl2hex(h, s, l){
	colorsample = hslToRgb(h, s, l);
	colhex = rgbToHex(colorsample[0], colorsample[1], colorsample[2]);
	return colhex;
}
Example of use
var xpos, ypos;

for(var i = 0; i < 100; i++){
	for(var j = 0; j < 10; j++){
		ctx.beginPath();
		xpos = 175 + (20+j*17) * Math.cos((i*3.6)*(Math.PI/180));
		ypos = 175 + (20+j*17) * Math.sin((i*3.6)*(Math.PI/180));
		ctx.arc(xpos, ypos, 10, 0, 2*Math.PI, true);
		ctx.fillStyle = hsl2hex(i*0.01, 0.1*j, 0.5);
		ctx.fill();
	}
}

Creative Commons License
Filmmaskiner.dk by Kasper Lauritzen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
(unless other is noted)