Analysis on using Javascript to obtain random colors

Source: Internet
Author: User

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

 
 
  1. var getRandomColor = function(){    
  2. return  '#' +      
  3. (function(color){      
  4. return (color +=  '0123456789abcdef'[Math.floor(Math.random()*16)])        
  5. && (color.length == 6) ?  color : arguments.callee(color);    
  6. })('');   

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

 
 
  1. var getRandomColor = function(){    
  2. return (function(m,s,c){    
  3. return (c ? arguments.callee(m,s,c-1) : '#') +        
  4. s[m.floor(m.random() * 16)]   
  5. })(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

 
 
  1. Array.prototype.map = function(fn, thisObj) {    
  2. var scope = thisObj || window;   
  3. var a = [];    
  4. for ( var i=0, j=this.length; i < j; ++i ) {      
  5. a.push(fn.call(scope, this[i], i, this));    
  6. }    
  7. return a;   
  8. };   
  9. var getRandomColor = function(){   
  10. return '#'+'0123456789abcdef'.split('').map(function(v,i,a){       
  11. 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

 
 
  1. var getRandomColor = function(){    
  2. 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.

 
 
  1. <! Doctype html> 
  2. <Meta Charset="UTF-8"/> 
  3. <Meta Http-equiv="X-UA-Compatible" Content="IE = 8"/> 
  4. <Title>Maximum Value of hex</Title> 
  5. <Script Type="Text/javascript" Charset="UTF-8"> 
  6. Window. onload=Function(){
  7. Alert (parseInt ("0 xffffff", 16). toString (10 ));
  8. };
  9. </Script> 
  10. <Div Id="Text"></Div> 

Run code

Implementation 5

 
 
  1. var getRandomColor = function(){    
  2. 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

 
 
  1. var getRandomColor = function(){   
  2. return '#'+(function(h){     
  3. return new Array(7-h.length).join("0")+h   
  4. })((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

 
 
  1. var getRandomColor = function(){   
  2. 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

 
 
  1. var getRandomColor = function(){      
  2. return "hsb(" + Math.random()  + ", 1, 1)";   

Practice:

 
 
  1. <! Doctype html>
  2. <Html dir ="Ltr"Lang ="Zh-CN">
  3. <Head>
  4. <Meta charset ="UTF-8"/>
  5. <Meta http-equiv ="X-UA-Compatible"Content ="IE = 8">
  6. <Title> Primary pie chart </title>
  7. <Script src =Http://bloghighlighter.googlecode.com/files/raphael-min.js"Type ="Text/javascript"> </Script>
  8. <Script type ="Text/javascript"Charset ="UTF-8">
  9.  
  10. VarGetRandomColor =Function(){
  11. Return "Hsb ("+ Math. random () +", 1, 1 )";
  12. }
  13.  
  14. Window. onload =Function(){
  15. VarPaper = Raphael ("Canvas", 700,700 );
  16. Paper. rect (0, 0,640,480, 10). attr ({fill:"# F2F1D7", Stroke:"None"});// Set the canvas 
  17.  
  18. FunctionDrawSector (cx, cy, r, paper, oc, startAngle ){
  19. VarAngleplus = 360 * oc/100,// Multiply 360 degrees by 40% 
  20. StartAngle = startAngle | 0,
  21. EndAngle = startAngle + angleplus,
  22. Rad = Math. PI/180,
  23. X1 = cx + r * Math. cos (-startAngle * rad ),
  24. X2 = cx + r * Math. cos (-endAngle * rad ),
  25. Y1 = cy + r * Math. sin (-startAngle * rad ),
  26. Y2 = cy + r * Math. sin (-endAngle * rad );
  27. VarPath = ["M", Cx, cy,"L", X1, y1,"", R, r, 0, + (endAngle-startAngle> 180), 0, x2, y2,"Z"];
  28. Path = path. join ("");
  29. Paper. path ({fill: getRandomColor ()}, path );
  30. ReturnEndAngle
  31. }
  32. VarOcs = [, 8];
  33. For(VarI = 0, l = ocs. length, startAngle; I <l; I ++ ){
  34. StartAngle = drawSector (300,300,100, paper, ocs [I], startAngle );
  35. }
  36.  
  37. };
  38. </Script>
  39. <Style type ="Text/css"Media ="Screen"> 
  40. # Canvas { 
  41. Width: 700px;
  42. Height: 700px;
  43. }
  44. </Style>
  45. <Title> Primary pie chart </title>
  46. </Head>
  47. <Body>
  48. <P> Primary pie chart </p>
  49. <Div id ="Canvas"> </Div>
  50. </Body>
  51. </Html>

Run code

Original article title: javascript to obtain random colors

Link: http://www.cnblogs.com/rubylouvre/archive/2009/09/24/1572977.html

  1. What is JSON? Data format prepared for JavaScript
  2. 10 most commonly used JavaScript udfs
  3. Some extended thoughts on loading JavaScript events
  4. Summary of JavaScript usage: From BOM and DOM
  5. How ExtJS works on Android Simulators

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.