Random color generation and conversion between hexadecimal color and RGB color values

Source: Internet
Author: User

/**

* Random COLOR GENERATION

* @ Return the random hexadecimal color.

*/


Function randomColor (){

Var colorStr = Math. floor (Math. random () * 0 xFFFFFF). toString (16). toUpperCase ();

Return "#" + "000000". substring (-6-colorStr) + colorStr;

}

 

/**

* Convert hexadecimal color to RGB color

* @ Param color the hexadecimal color to be converted

* @ Return RGB color


Function colorHexToRGB (color ){

Color = color. toUpperCase ();

Var regexpHex =/^ # [0-9a-fA-F] {3, 6} $/; // Hex

If (regexpHex. test (color )){

Var hexArray = new Array ();

Var count = 1;

For (var I = 1; I <= 3; I ++ ){

If (color. length-2 * I> 3-i ){

HexArray. push (Number ("0x" + color. substring (count, count + 2 )));

Count + = 2;

} Else {

HexArray. push (Number ("0x" + color. charAt (count) + color. charAt (count )));

Count + = 1;

}

}

Return "RGB (" + hexArray. join (",") + ")";

} Else {

Return color;

}

}

 

/**

* Convert RGB color to hexadecimal color

* @ Param color the RGB color to be converted

* @ Return hexadecimal color

*/


Function colorRGBToHex (color ){

Var regexpRGB =/^ (rgb | RGB) \ ([0-9] {1, 3}, \ s? [0-9] {1, 3}, \ s? [0-9] {1, 3} \) $/; // RGB

If (regexpRGB. test (color )){

Color = color. replace (/(\ (| \) | rgb | RGB) */g, ""). split (",");

Var colorHex = "#";

For (var I = 0; I <color. length; I ++ ){

Var hex = Number (color [I]). toString (16 );

If (hex. length = 1) hex = "0" + hex;

ColorHex + = hex;

}

Return colorHex;

} Else {

Return color;

}

}

 

From the dark day, how do you understand the dark night?

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.