This article will talk about how to use Javascript to obtain random colors. here we need to know that Javascript to obtain random colors is mainly used for easy display during plotting. I hope you can get help from this article.
When creating a pie chart or a label cloud, we usually need many colors in two ways. One is to prepare a set of beautiful candidate colors, and the other is to randomly generate colors. When there are many or unknown numbers, I think the latter is the only way out. Google sorted it out as follows.
Implementation 1
- 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
- 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
- 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 extend the array. map will return an array, and then we use join to concatenate its elements into characters.
Implementation 4
- 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 numbers, which are equivalent to "0x000000" to "0 xffffff ". 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.
- <! 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>
Run code
Implementation 5
- var getRandomColor = function(){
- return '#'+(Math.random()*0xffffff<<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
- var getRandomColor = function(){
- return '#'+(function(h){
- return new Array(7-h.length).join("0")+h
- })((Math.random()*0x1000000<<0).toString(16))
- }
Fixed the issue that the above version bug could not generate pure white and insufficient hex digits ). 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 6 bits, and directly fill in zero without bits.
Implementation 7
- var getRandomColor = function(){
- return '#'+('00000'+(Math.random()*0x1000000<<0).toString(16)).substr(-6);
- }
This time, we made up zero in front and saved the recursive detection.
The color range generated in the above version is large and complete, but the problem is that the color is not easy to see, so 8 came out. The color it generates is quite bright.
Implementation 8
- var getRandomColor = function(){
- return "hsb(" + Math.random() + ", 1, 1)";
- }
Practice:
- <! Doctype html>
- <Html dir ="Ltr"Lang ="Zh-CN">
- <Head>
- <Meta charset ="UTF-8"/>
- <Meta http-equiv ="X-UA-Compatible"Content ="IE = 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">
-
- VarGetRandomColor =Function(){
- Return "Hsb ("+ Math. random () +", 1, 1 )";
- }
-
- Window. onload =Function(){
- VarPaper = Raphael ("Canvas", 700,700 );
- Paper. rect (0, 0,640,480, 10). attr ({fill:"# F2F1D7", Stroke:"None"});// Set the canvas
-
- FunctionDrawSector (cx, cy, r, paper, oc, startAngle ){
- VarAngleplus = 360 * oc/100,// Multiply 360 degrees 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 );
- VarPath = ["M", Cx, cy,"L", X1, y1,"", R, r, 0, + (endAngle-startAngle> 180), 0, x2, y2,"Z"];
- Path = path. join ("");
- Paper. path ({fill: getRandomColor ()}, path );
- ReturnEndAngle
- }
- VarOcs = [, 8];
- For(VarI = 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 pie chart </title>
- </Head>
- <Body>
- <P> Primary pie chart </p>
- <Div id ="Canvas"> </Div>
- </Body>
- </Html>
Run code
Original article title: javascript to obtain random colors
Link: http://www.cnblogs.com/rubylouvre/archive/2009/09/24/1572977.html
- What is JSON? Data format prepared for JavaScript
- 10 most commonly used JavaScript udfs
- Some extended thoughts on loading JavaScript events
- Summary of JavaScript usage: From BOM and DOM
- How ExtJS works on Android Simulators