Using Javascript to convert colors from rgb to hexadecimal, javascriptrgb
This article describes how to convert colors from rgb to hexadecimal in Javascript. Share it with you for your reference. The details are as follows:
Usage:
Color(12,34,56);Color("#fff")Color("#defdcd")
Implementation Code:
// Color conversion var Color = function () {if (! (This instanceof Color) {var color = new Color (); color. _ init. apply (color, arguments); return color;} if (arguments. length) {this. _ init. apply (this, arguments) ;}// set get, set Method var methods = ["red", "green", "blue", "colorValue"]; var defineSetGetMethod = function (fn, methods) {var fnPrototype = fn. prototype; for (var I = 0; I <methods. length; I ++) {var methodName = methods [I]. charAt (0 ). toLocal EUpperCase () + methods [I]. substring (1); fn. prototype ['set' + methodName] = new Function ("value", "this. "+ methods [I] +" = value; "); fn. prototype ['get' + methodName] = new Function ("return this. "+ methods [I] +"; "); fn. prototype ['string'] = new Function ('Return "rgb (" + this. red + "," + this. green + "," + this. blue + ")"; ') ;}}; defineSetGetMethod (Color, methods); // The Extension function's instance method var extend = function (fn, option) {Var fnPrototype = fn. prototype; for (var I in option) {fnPrototype [I] = option [I] ;}}; extend (Color, {_ init: function () {if (arguments. length = 3) {this. red = arguments [0]; this. green = arguments [1]; this. blue = arguments [2]; this. getColorValue ();} else {var colorValue = arguments [0]. replace (/^ \ # {1}/, ""); if (colorValue. length = 3) {colorValue = colorValue. replace (/(.) /g, '$1 $ 1');} t His. red = parseInt ('0x '+ colorValue. substring (0, 2), 16); this. green = parseInt ('0x '+ colorValue. substring (2, 4), 16); this. blue = parseInt ('0x '+ colorValue. substring (4), 16); this. colorValue = "#" + colorValue ;}, getColorValue: function () {if (this. colorValue) {return this. colorValue;} var hR = this. red. toString (16); var hG = this. green. toString (16); var hB = this. blue. toString (16); ret Urn this. colorValue = "#" + (this. red <16? ("0" + hR): hR) + (this. green <16? ("0" + hG): hG) + (this. blue <16? ("0" + hB): hB );}});
I hope this article will help you design javascript programs.