A variety of ways to implement JS random color code _javascript skills

Source: Internet
Author: User
Tags closure cos sin

JS random color has a lot of places to use: For example, we see a lot of label connections are colorful. That's the one that needs to be here. Here's the start:

There are two ways of thinking. one is to prepare a beautiful set of candidate colors, the second is to generate color randomly .

Achieve 1

Copy Code code as follows:

var getrandomcolor = function () {

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

Randomly generated 6 characters and then strung together, the closure of the call itself and ternary operators to let the program become introverted, beginner's mind should be good to learn this writing.

Achieve 2

Copy Code code 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)
}

Extracts the Math object, the string used to generate the hex color value, and uses the third parameter to determine whether the call itself continues.

Achieve 3

Copy Code code as follows:

The following are the referenced contents:

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 A;
};
var getrandomcolor = function () {
Return ' # ' + ' 0123456789abcdef '. Split ('). Map (function (v,i,a) {
Return i>5? Null:a[math.floor (Math.random () *16)]}. Join (");
}


This requires us to make some extensions to the array, and the map will return a list, and then we'll use the join to string its elements into characters.

Achieve 4

Copy Code code as follows:

The following are the referenced contents:

var getrandomcolor = function () {

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


This implementation is very inverse day, although a little bug. We know that the hex color value is from #000000 to #ffffff, and the six digits in the back are 16 in number, the equivalent of "0x000000" to "0XFFFFFF". The idea is to convert the maximum value of hex to 10 ffffff first, then random and then convert back to 16. Let's take a look at how to get the value of 16777215.
Copy Code code as follows:

The following are the referenced contents:

<!doctype html>
<meta charset= "Utf-8"/>
<meta http-equiv= "x-ua-compatible" content= "ie=8"/>
Maximum value of <title>hex </title>
<script type= "Text/javascript" charset= "Utf-8" >
Window.onload = function () {
Alert (parseint ("0xFFFFFF"). ToString (10));
};
</script>
<div id= "Text" ></div>


Achieve 5
Copy Code code as follows:

The following are the referenced contents:

var getrandomcolor = function () {

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


The basic implementation of the 4 improvement, using the left shift operator to convert 0XFFFFFF to integral type. So you don't have to remember 16777215. Since the precedence of the left-shift operator is not as high as multiplication, it is not even math.floor to move left after random.

Achieve 6

Copy Code code as follows:

The following are the referenced contents:

var getrandomcolor = function () {

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


Fix the bug in the previous version (no pure white and hex number problem). 0x1000000 is quite 0xffffff+1, ensuring that it will be selected to 0XFFFFFF. In the closure we deal with the problem that the hex value is less than 5 digits, directly in the position of 0.

Achieve 7

Copy Code code as follows:

The following are the referenced contents:

var getrandomcolor = function () {

Return ' # ' + (' 00000 ' + (Math.random () *0x1000000<<0). ToString (). substr (-6);
}


This time in front of 0, even recursive detection also saved.

Actual combat:

Copy Code code as follows:

The following are the referenced contents:

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01//en" "Http://www.w3.org/TR/html4/strict.dtd"
  <HEAD>
    <meta http-equiv= "Content-type content=" text/html 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 ' # ' + (' 00000 ' +) (Math.random () *0x1000000<<0) . toString). substr (-6);
     }

Window.onload = function () {
var paper = Raphael ("Canvas", 700, 700);
Paper.rect (0, 0, 640, 480,10). attr ({fill: "#F2F1D7", Stroke: "None"});/Set Artboard

function Drawsector (cx,cy,r,paper,oc,startangle) {
var angleplus = 360 * oc/100,//360 degree 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 = [40,25,17,10,8];
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> Primary 2324234 pie chart </title>
<body>
<p> Primary 23232 Pie chart </p>
<div id= "Canvas" ></div>
</body>

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.