JavaScript implements hexadecimal color value (HEX) and RGB format conversion _javascript tips

Source: Internet
Author: User
Tags color gamut

In daily development, the conversion between color gamut values in different formats is often used, and a workaround is given below.

Copy Code code as follows:

Regular expressions for hexadecimal color values
var reg =/^# ([0-9a-fa-f]{3}|[ 0-9A-FA-F]{6}) $/;
/*rgb Color conversion to 16
String.prototype.colorHex = function () {
var that = this;
if (/^ (rgb| RGB)/.test (that)) {
var acolor = That.replace (/(?: \ (|\) |rgb| RGB) */g, ""). Split (",");
var strhex = "#";
for (var i=0; i<acolor.length; i++) {
var hex = number (Acolor). toString (16);
if (hex = = "0") {
Hex + = hex;
}
Strhex + = hex;
}
if (strhex.length!== 7) {
Strhex = that;
}
return strhex;
}else if (reg.test (that)) {
var anum = That.replace (/#/, ""). Split ("");
if (anum.length = = 6) {
return to that;
}else if (anum.length = = 3) {
var numhex = "#";
for (var i=0; i<anum.length; i+=1) {
Numhex + = (anum+anum);
}
return numhex;
}
}else{
return to that;
}};
/*16 color into RGB format * *
STRING.PROTOTYPE.COLORRGB = function () {
var scolor = This.tolowercase ();
if (Scolor && reg.test (scolor)) {
if (scolor.length = = 4) {
var scolornew = "#";
for (var i=1; i<4; i+=1) {
Scolornew + + scolor.slice (i,i+1). Concat (Scolor.slice (i,i+1));
}
Scolor = scolornew;
}
Working with six-bit color values
var scolorchange = [];
for (var i=1; i<7; i+=2) {
Scolorchange.push (parseint ("0x" +scolor.slice (i,i+2));
}
Return "RGB (" + Scolorchange.join (",") + ")";
}else{
return scolor;
}};

To use the color conversion method:
Copy Code code as follows:

Ar sRgb = "RGB (245, the)", ShEx = "#34538b";
var shexcolor = Srgb.colorhex ();
var srgbcolor = Shex.colorrgb ();

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.