Librairie de gestion des couleurs pour css : colorparser

Description

Ceci est une petite librairie qui reconnait tous les formats de couleurs possible jusqu'à CSS3.
Elle vous permettra de modifier une couleur existante ou d'en créer une nouvelle pour ensuite faire un sortie vers l'un des format gérer par CSS3.

Exemples :
var color = new colorParser(' 9acd32 ');
color.toName() // yellowgreen
color.toHex() // #9acd32
color.toString() // yellowgreen
color.toRGB() // rgb(154, 205, 50)
color.toRGBA() // rgba(154, 205, 50, 1)
color.toHSL() // hsl(80, 61%, 50%)
color.toHSLA() // hsla(80, 61%, 50%, 1)

// les fonction suivantes sont des getters et des setters, on peut leur passer un paramètre pour modifier la couleur.
color.red() // 154
color.green() // 205
color.blue() // 50
color.hue() // 79.74193548387098
color.saturation() // 0.607843137254902
color.lightness() // 0.5
color.alpha() // 1

// indique si la couleur parser est valid ou pas.
color.valid // true

Demo visible ici : http://www.coopmcs.com/demo/colorParser/colorParser.html
Demo visible ici : http://www.coopmcs.com/demo/colorParser/colorParser2.html
Demo color picker : http://www.coopmcs.com/demo/colorParser/colorPicker.html
Demo color picker facon AI : http://www.coopmcs.com/demo/colorParser/colorPickerAI.html

Cette librairie a été inspirée par http://www.phpied.com/rgb-color-parser-in-javascript/ a laquelle j'ai rajouté la gestion des HSL et du canal alpha.

Source / Exemple :


// valid color are :
//		hex color    Example : FFAB50 ou #FFAB52 ou F5F ou #F3F
//		rgb color    Example : rgb(0,255,0)
//		rgba color   Example : rgba(0,255,56,0.5)
//      rgb % color  Example : rgb(100%, 0%, 0%)
//		rgba % color Example : rgba(15%,10%,56%,0.5)
//		hsl color    Example : hsl(0, 100%, 50%)
//		hsla color   Example : hsla(120, 100%, 50%, 0.3)
//		named color  Example : lime

function colorParser(color) {

	this.valid = false;
	this.r     = 0; // red			0->255
	this.g     = 0; // green		0->255
	this.b     = 0; // blue			0->255
	this.h     = 0; // hue			0->360
	this.s     = 0; // saturation	0->1
	this.l     = 0; // lightness	0->1
	this.a     = 1; // alpha		0->1

	this.setHSLfromRGB = function () {
		var tmp = RGBtoHSL(this.r,this.g,this.b);
		this.h = tmp[0];		this.s = tmp[1];		this.l = tmp[2];
	}

	this.setRGBfromHSL = function () {
		var tmp = HSLtoRGB(this.h,this.s,this.l);
		this.r = tmp[0];		this.g = tmp[1];		this.b = tmp[2];
	}

	// clear and lower case the param
	color = color.replace(/ |#/g,'').toLowerCase();

	// liste des couleurs valident en HTML
	// get from http://www.phpied.com/rgb-color-parser-in-javascript/
	var named_colors = {aliceblue:'f0f8ff',antiquewhite:'faebd7',aqua:'00ffff',aquamarine:'7fffd4',azure:'f0ffff',beige:'f5f5dc',bisque:'ffe4c4',black:'000000',blanchedalmond:'ffebcd',blue:'0000ff',blueviolet:'8a2be2',brown:'a52a2a',burlywood:'deb887',cadetblue:'5f9ea0',chartreuse:'7fff00',chocolate:'d2691e',coral:'ff7f50',cornflowerblue:'6495ed',cornsilk:'fff8dc',crimson:'dc143c',cyan:'00ffff',darkblue:'00008b',darkcyan:'008b8b',darkgoldenrod:'b8860b',darkgray:'a9a9a9',darkgreen:'006400',darkkhaki:'bdb76b',darkmagenta:'8b008b',darkolivegreen:'556b2f',darkorange:'ff8c00',darkorchid:'9932cc',darkred:'8b0000',darksalmon:'e9967a',darkseagreen:'8fbc8f',darkslateblue:'483d8b',darkslategray:'2f4f4f',darkturquoise:'00ced1',darkviolet:'9400d3',deeppink:'ff1493',deepskyblue:'00bfff',dimgray:'696969',dodgerblue:'1e90ff',feldspar:'d19275',firebrick:'b22222',floralwhite:'fffaf0',forestgreen:'228b22',fuchsia:'ff00ff',gainsboro:'dcdcdc',ghostwhite:'f8f8ff',gold:'ffd700',goldenrod:'daa520',gray:'808080',green:'008000',greenyellow:'adff2f',honeydew:'f0fff0',hotpink:'ff69b4',indianred:'cd5c5c',indigo:'4b0082',ivory:'fffff0',khaki:'f0e68c',lavender:'e6e6fa',lavenderblush:'fff0f5',lawngreen:'7cfc00',lemonchiffon:'fffacd',lightblue:'add8e6',lightcoral:'f08080',lightcyan:'e0ffff',lightgoldenrodyellow:'fafad2',lightgrey:'d3d3d3',lightgreen:'90ee90',lightpink:'ffb6c1',lightsalmon:'ffa07a',lightseagreen:'20b2aa',lightskyblue:'87cefa',lightslateblue:'8470ff',lightslategray:'778899',lightsteelblue:'b0c4de',lightyellow:'ffffe0',lime:'00ff00',limegreen:'32cd32',linen:'faf0e6',magenta:'ff00ff',maroon:'800000',mediumaquamarine:'66cdaa',mediumblue:'0000cd',mediumorchid:'ba55d3',mediumpurple:'9370d8',mediumseagreen:'3cb371',mediumslateblue:'7b68ee',mediumspringgreen:'00fa9a',mediumturquoise:'48d1cc',mediumvioletred:'c71585',midnightblue:'191970',mintcream:'f5fffa',mistyrose:'ffe4e1',moccasin:'ffe4b5',navajowhite:'ffdead',navy:'000080',oldlace:'fdf5e6',olive:'808000',olivedrab:'6b8e23',orange:'ffa500',orangered:'ff4500',orchid:'da70d6',palegoldenrod:'eee8aa',palegreen:'98fb98',paleturquoise:'afeeee',palevioletred:'d87093',papayawhip:'ffefd5',peachpuff:'ffdab9',peru:'cd853f',pink:'ffc0cb',plum:'dda0dd',powderblue:'b0e0e6',purple:'800080',red:'ff0000',rosybrown:'bc8f8f',royalblue:'4169e1',saddlebrown:'8b4513',salmon:'fa8072',sandybrown:'f4a460',seagreen:'2e8b57',seashell:'fff5ee',sienna:'a0522d',silver:'c0c0c0',skyblue:'87ceeb',slateblue:'6a5acd',slategray:'708090',snow:'fffafa',springgreen:'00ff7f',steelblue:'4682b4',tan:'d2b48c',teal:'008080',thistle:'d8bfd8',tomato:'ff6347',turquoise:'40e0d0',violet:'ee82ee',violetred:'d02090',wheat:'f5deb3',white:'ffffff',whitesmoke:'f5f5f5',yellow:'ffff00',yellowgreen:'9acd32'};
	var capture = new Array();
	
	// FF45AB css notation : FFAB50
	if (capture = color.match(/^([A-F\d]{2})([A-F\d]{2})([A-F\d]{2})$/i)) {
		this.r = hex2dec(capture[1]);
		this.g = hex2dec(capture[2]);
		this.b = hex2dec(capture[3]);
		this.a = 1;
		this.setHSLfromRGB();
		this.valid = true;
	}
	// F4B css notation : F5F
	else if(capture = color.match(/^([A-F\d])([A-F\d])([A-F\d])$/i)) {
		this.r = hex2dec(capture[1].toString() + capture[1].toString());
		this.g = hex2dec(capture[2].toString() + capture[2].toString());
		this.b = hex2dec(capture[3].toString() + capture[3].toString());
		this.a = 1;
		this.setHSLfromRGB();
		this.valid = true;
	}
	// RGB css notation : rgb(0,255,0)
	else if(capture = color.match(/^rgb\((\d+),(\d+),(\d+)\)$/i)) {
		this.r = capture[1];
		this.g = capture[2];
		this.b = capture[3];
		this.a = 1;
		this.setHSLfromRGB();
		this.valid = true;
	}
	// RGBA css notation : rgba(0,255,56,0.5)
	else if(capture = color.match(/^rgba\((\d+),(\d+),(\d+),([\d\.]+)\)$/i)) {
		this.r = capture[1];
		this.g = capture[2];
		this.b = capture[3];
		this.a = capture[4];
		this.setHSLfromRGB();
		this.valid = true;
	}
	// RGB % css notation : rgb(100%, 0%, 0%)
	else if(capture = color.match(/^rgb\(([\d\.]+)%,([\d\.]+)%,([\d\.]+)%\)$/i)) {
		this.r = capture[1]/100*255;
		this.g = capture[2]/100*255;
		this.b = capture[3]/100*255;
		this.a = 1;
		this.setHSLfromRGB();
		this.valid = true;
	}
	// RGBA % css notation : rgba(15%,10%,56%,0.5)
	else if(capture = color.match(/^rgba\(([\d\.]+)%,([\d\.]+)%,([\d\.]+)%,([\d\.]+)\)$/i)) {
		this.r = capture[1]/100*255;
		this.g = capture[2]/100*255;
		this.b = capture[3]/100*255;
		this.a = capture[4];
		this.setHSLfromRGB();
		this.valid = true;
	}
	// HSL css notation : hsl(0, 100%, 50%)
	else if(capture = color.match(/^hsl\(([\d\.]+),([\d\.]+)%,([\d\.]+)%\)$/i)) {
		this.h = capture[1];
		this.s = capture[2]/100;
		this.l = capture[3]/100;
		this.a = 1;
		this.setRGBfromHSL();
		this.valid = true;
	}
	// HSLA css notation : hsla(120, 100%, 50%, 0.3)
	else if(capture = color.match(/^hsla\(([\d\.]+),([\d\.]+)%,([\d\.]+)%,([\d\.]+)\)$/i)) {
		this.h = capture[1];
		this.s = capture[2]/100;
		this.l = capture[3]/100;
		this.a = capture[4];
		this.setRGBfromHSL();
		this.valid = true;
	}
	// Named color css notation : darkblue
	else if(color in named_colors) { // nom de couleur en clair
		capture = /^([A-F\d]{2})([A-F\d]{2})([A-F\d]{2})$/i.exec(named_colors[color]);
		this.r = hex2dec(capture[1]);
		this.g = hex2dec(capture[2]);
		this.b = hex2dec(capture[3]);
		this.a = 1;
		this.setHSLfromRGB();
		this.valid = true;
	}

	// #AB56DE
	this.toHex = function ()	{ return '#' + dec2hex(this.r) + dec2hex(this.g) + dec2hex(this.b);  }

	// rgb(xxx,xxx,xxx)
    this.toRGB = function()		{ return  'rgb(' + Math.round(this.r) + ', ' + Math.round(this.g) + ', ' + Math.round(this.b) + ')'; }

	// rgba(xxx,xxx,xxx,10%)
    this.toRGBA = function()	{ return 'rgba(' + Math.round(this.r) + ', ' + Math.round(this.g) + ', ' + Math.round(this.b) + ', ' + this.a +')'; }

	// hsl(50,20%,50%)
    this.toHSL = function()		{ return  'hsl(' + Math.round(this.h) + ', ' + Math.round(this.s * 100) + '%, ' + Math.round(this.l * 100) + '%)'; }

	// hsla(50,20%,50%,0.2)
    this.toHSLA = function()	{ return 'hsla(' + Math.round(this.h) + ', ' + Math.round(this.s * 100) + '%, ' + Math.round(this.l * 100) + '%, ' + this.a +')'; }

	// darkblue
    this.toName = function () {
		var search_hexcode = this.toHex().substring(1,7); // supprime le leading '#'
		for (var name in named_colors) {
			if (named_colors[name] == search_hexcode)
				return name;
		}
        return '';
    }

	// overloading toString : darblue or #456581
	this.toString = function () {
		var tmp = this.toName();
		return tmp ? tmp : this.toHex();
    }

	

	// getters and setters
	this.red		= function (param) {
		if			(typeof param == 'number') { // setter
			var old = this.r;
			if		(param > 255) param = 255 ; // [0->255]
			else if (param < 0)   param = 0;
			this.r = param;
			this.setHSLfromRGB();
			return old;
		} else if	(typeof param == 'undefined') { // getter
			return this.r;
		}
	}

	this.green		= function (param) {
		if			(typeof param == 'number') { // setter
			var old = this.g;
			if		(param > 255) param = 255 ; // [0->255]
			else if (param < 0)   param = 0;
			this.g = param;
			this.setHSLfromRGB();
			return old;
		} else if	(typeof param == 'undefined') { // getter
			return this.g;
		}
	}

	this.blue		= function (param) {
		if			(typeof param == 'number') { // setter
			var old = this.b;
			if		(param > 255) param = 255 ; // [0->255]
			else if (param < 0)   param = 0;
			this.b = param;
			this.setHSLfromRGB();
			return old;
		} else if	(typeof param == 'undefined') { // getter
			return this.b;
		}
	}

	this.hue		= function (param) {
		if			(typeof param == 'number') { // setter	
			var old = this.h;
			if		(param > 360) param %= 360 ; // [0->360]
			else if (param < 0)
				while(param < 0) param += 360;
			this.h = param;
			this.setRGBfromHSL();
			return old;
		} else if	(typeof param == 'undefined') { // getter
			return this.h;
		}
	}

	this.saturation	= function (param) {
		if			(typeof param == 'number') { // setter
			var old = this.s;
			if		(param > 1) param = 1 ; // [0->1]
			else if (param < 0) param = 0;
			this.s = param;
			this.setRGBfromHSL();
			return old;
		} else if	(typeof param == 'undefined') { // getter
			return this.s;
		}
	}

	this.lightness	= function (param) {
		if			(typeof param == 'number') { // setter
			var old = this.l;
			if		(param > 1) param = 1 ; // [0->1]
			else if (param < 0) param = 0;
			this.l = param;
			this.setRGBfromHSL();
			return old;
		} else if	(typeof param == 'undefined') { // getter
			return this.l;
		}
	}

	this.alpha	= function (param) {
		if			(typeof param == 'number') { // setter
			var old = this.a;
			if		(param > 1) param = 1 ; // [0->1]
			else if (param < 0) param = 0;
			this.a = param;
			return old;
		} else if	(typeof param == 'undefined') { // getter
			return this.a;
		}
	}

	

	// private fonctions
	function dec2hex(s)	{ return ( s<15.5 ? '0' : '' ) + Math.round( s ).toString( 16 ); }
	function hex2dec(s)	{ return parseInt( s, 16 ); }

	function RGBtoHSL(r,g,b) {
		/* algorithms from http://130.113.54.154/~monger/hsl-rgb.html */
		var h,s,l;
		var pourcent = new Array(r/255, g/255, b/255);
		var min = Math.min(pourcent[0],pourcent[1],pourcent[2]);
		var max = Math.max(pourcent[0],pourcent[1],pourcent[2]);

		l = (max + min)/2;
 
		if (max == min) { // grey saturation=0, hue=0
			s = 0;
			h = 0;
		} else if (l < 0.5) {
			s = (max - min) / (max + min);
		} else {
			s = (max - min) / (2 - max - min);
		}
		
		if		(max == pourcent[0]) h =	 (pourcent[1]-pourcent[2]) / (max - min);
		else if (max == pourcent[1]) h = 2 + (pourcent[2]-pourcent[0]) / (max - min);
		else if (max == pourcent[2]) h = 4 + (pourcent[0]-pourcent[1]) / (max - min);
		h *= 60 ;
		if (h < 0) h += 360;
		if(isNaN(h)) h=0;
		
		return new Array(h,s,l);
	}

	function HSLtoRGB (h,s,l) {
		/* algorithms from http://130.113.54.154/~monger/hsl-rgb.html */
		if (s == 0)
			return new Array(Math.round(l*255),Math.round(l*255),Math.round(l*255));

		var temp2 = (l < 0.5) ? l * (1+s) : l + s - l*s ;
		var temp1 = 2*l - temp2;

		h /= 360 ;

		var temp3 = new Array(h + 1/3,  h,  h - 1/3);
		for(var i=0 ; i<temp3.length ; i++) {
			if (temp3[i] < 0) temp3[i] += 1;
			if (temp3[i] > 1) temp3[i] -= 1;
		}
	
		var rgb = new Array(0,0,0);
		for(var i=0 ; i<rgb.length ; i++) {
			if		(6 * temp3[i] < 1)	rgb[i] = temp1 + (temp2-temp1) * 6 * temp3[i];
			else if (2 * temp3[i] < 1)  rgb[i] = temp2;
			else if (3 * temp3[i] < 2)  rgb[i] = temp1 + (temp2-temp1) * (2/3 - temp3[i]) * 6;
			else						rgb[i] = temp1;
			rgb[i] = Math.round(rgb[i] * 255) ;
		}

		return new Array(rgb[0],rgb[1],rgb[2]);
	}
}

Codes Sources

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.