Js get random color value

Source: Internet
Author: User

[Javascript]
/*
* Obtain random color values
* @ Param min, minimum value, value range: 0-255
* @ Param max; maximum value; value range: 0-255
*/
Function getColor (min, max ){
Var co = "";
Co + = (getRandom (min, max) + ",");
Co + = (getRandom (min, max) + ",");
Co + = getRandom (min, max );
Return RGB2Hex (co );
}
 
/*
* Obtain random numbers within a specified range
* @ Param min, minimum value
* @ Param max, maximum value
*/
 
Function getRandom (min, max ){
// Upper limit of x and lower limit of y
Var x = max;
Var y = min;
If (x <y ){
X = min;
Y = max;
}
Var rand = parseInt (Math. random () * (x-y + 1) + y );
Return rand;
}
 
/*
* Obtain the color value.
* @ Param rgb, RGB color value, for example, "23,189,246"
*/
Function RGB2Hex (rgb ){
Var re = rgb. replace (/(? : \ (| \) | Rgb | RGB) */g, ""). split (","); // remove unnecessary parts using regular expressions
Var hexColor = "#";
Var hex = ['0', '1', '2', '3', '4', '5', '6', '7', '8 ', '9', 'A', 'B', 'C', 'D', 'E', 'F'];
For (var I = 0; I <3; I ++ ){
Var r = null;
Var c = re [I];
Var hexAr = [];
While (c> 16 ){
R = c % 16;
C = (c/16)> 0;
HexAr. push (hex [r]);
}
HexAr. push (hex [c]);
HexColor + = hexAr. reverse (). join ('');
}
Return hexColor;

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.