Multiple implementation methods of js random color code

Source: Internet
Author: User

Javascript random colors are used in many places: for example, many tag connections are colorful. That's all we need. Start as follows:

There are two methods in total.One is to prepare a set of beautiful candidate colors, and the other is to randomly generate colors..

Implementation 1
Copy codeThe Code is as follows:
Var getRandomColor = function (){

Return '#' +
(Function (color ){
Return (color + = '0123456789abcdef '[Math. floor (Math. random () * 16)])
& (Color. length = 6 )? Color: arguments. callee (color );
})('');
}

The six characters are randomly generated and then stringed together. The closure calls itself and the ternary operator make the program restrained. Beginners should study this method well.

Implementation 2

Copy codeThe Code is as follows:
Var getRandomColor = function (){

Return (function (m, s, c ){
Return (c? Arguments. callee (m, s, C-1): '#') +
S [m. floor (m. random () * 16)]
}) (Math, '0123456789abcdef ', 5)
}

Extract the string that generates the hex color value from the Math object, and use the third parameter to determine whether to continue calling itself.

Implementation 3

Copy codeThe Code is as follows:
Reference content is as follows:

Array. prototype. map = function (fn, thisObj ){

Var scope = thisObj | window;
Var a = [];
For (var I = 0, j = this. length; I <j; ++ I ){
A. push (fn. call (scope, this [I], I, this ));
}
Return;
};
Var getRandomColor = function (){
Return '#' + '0123456789abcdef '. split (''). map (function (v, I, ){
Return I> 5? Null: a [Math. floor (Math. random () * 16)]}). join ('');
}

This requires us to extend the array. map will return an array, and then we use join to concatenate its elements into characters.

Implementation 4
Copy codeThe Code is as follows:
Reference content is as follows:

Var getRandomColor = function (){

Return '#' + Math. floor (Math. random () * 16777215). toString (16 );
}

This implementation is very backward, although a little bug. We know that the hex color value ranges from #000000 to # ffffff, And the next six digits are hexadecimal values, which are equivalent to "0x000000" to "0xffffff ". The idea of this implementation is to convert the maximum ffffff of hex into a 10-digit system first, and then convert it back to a 16-digit system after random. Let's take a look at how to get the value 16777215.
Copy codeThe Code is as follows:
Reference content is as follows:

<! Doctype html>
<Meta charset = "UTF-8"/>
<Meta http-equiv = "X-UA-Compatible" content = "IE = 8"/>
<Title> maximum value of hex </title>
<Script type = "text/javascript" charset = "UTF-8">
Window. onload = function (){
Alert (parseInt ("0 xffffff", 16). toString (10 ));
};
</Script>
<Div id = "text"> </div>

Implementation 5
Copy codeThe Code is as follows:
Reference content is as follows:

Var getRandomColor = function (){

Return '#' + (Math. random () * 0 xffffff <0). toString (16 );
}

Basic implementation 4 is improved, and 0xffffff is converted to an integer using the Left shift operator. In this way, you do not need to remember 16777215. Since the Left shift operator has a lower priority than the multiplication number, it is randomly moved to the left and no Math. floor is needed.

Implementation 6
Copy codeThe Code is as follows:
Reference content is as follows:

Var getRandomColor = function (){

Return '#' + (function (h ){
Return new Array (7-h.length). join ("0") + h
}) (Math. random () * 0x1000000 <0). toString (16 ))
}

Fixed the bug in the previous version (the problem of insufficient white and hex digits cannot be generated ). 0x000000 is equivalent to 0 xffffff + 1. Make sure that 0 xffffff is selected. In the closure, we deal with the problem that the hex value is less than five bits, and directly fill in zero without bits.

Implementation 7
Copy codeThe Code is as follows:
Reference content is as follows:

Var getRandomColor = function (){

Return '#' + ('000000' + (Math. random () * 0x00000 <0). toString (16). substr (-6 );
}

This time, we made up zero in front and saved the recursive detection.

Practice:
Copy codeThe Code is as follows:
Reference content is as follows:

<! DOCTYPE html PUBLIC "-// W3C // dtd html 4.01 // EN" "http://www.w3.org/TR/html4/strict.dtd">
<Html lang = "zh-cn">
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8">
<Title> Primary pie chart </title>
<Script src = "http://bloghighlighter.googlecode.com/files/raphael-min.js" type = "text/javascript"> </script>
<Script type = "text/javascript" charset = "UTF-8">
Var getRandomColor = function (){
Return '#' + ('000000' + (Math. random () * 0x00000 <0). toString (16). substr (-6 );
}

Window. onload = function (){
Var paper = Raphael ("canvas", 700,700 );
Paper. rect (0, 0,640,480, 10). attr ({fill: "# F2F1D7", stroke: "none"}); // set the canvas

Function drawSector (cx, cy, r, paper, oc, startAngle ){
Var angleplus = 360 * oc/100, // 360 degrees multiplied by 40%
StartAngle = startAngle | 0,
EndAngle = startAngle + angleplus,
Rad = Math. PI/180,
X1 = cx + r * Math. cos (-startAngle * rad ),
X2 = cx + r * Math. cos (-endAngle * rad ),
Y1 = cy + r * Math. sin (-startAngle * rad ),
Y2 = cy + r * Math. sin (-endAngle * rad );
Var path = ["M", cx, cy, "L", x1, y1, "A", r, r, 0, + (endAngle-startAngle> 180 ), 0, x2, y2, "z"],

Path = path. join ("");
Paper. path ({fill: getRandomColor ()}, path );
Return endAngle
}
Var ocs = [,];
For (var I = 0, l = ocs. length, startAngle; I <l; I ++ ){
StartAngle = drawSector (300,300,100, paper, ocs [I], startAngle );
}

};
</Script>
<Style type = "text/css" media = "screen">
# Canvas {
Width: 700px;
Height: 700px;
}
</Style>
<Title> 2324234 pie chart </title>
</Head>
<Body>
<P> 23232 pie chart </p>
<Div id = "canvas"> </div>
</Body>
</Html>

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.