淺析利用Javascript獲取隨機顏色
本文將談到利用Javascript獲取隨機顏色,這里我們需要知道做Javascript獲取隨機顏色主要是在作圖時方便展示,希望大家能從本文獲得幫助。
在制作餅圖或標簽云時,我們通常需要很多顏色,方法有二。一是準備一組漂亮的候選顏色,二是隨機生成顏色。在數量很多或不明確時,我想后者就是唯一的出路了。谷歌了一下,整理如下,按由淺入深的順序排列。
實現1
- var getRandomColor = function(){
- return '#' +
- (function(color){
- return (color += '0123456789abcdef'[Math.floor(Math.random()*16)])
- && (color.length == 6) ? color : arguments.callee(color);
- })('');
- }
隨機生成6個字符然后再串到一起,閉包調用自身與三元運算符讓程序變得內斂,初心者應該好好學習這種寫法。
實現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)
- }
把Math對象,用于生成hex顏色值的字符串提取出來,并利用第三個參數來判斷是否還繼續調用自身。
實現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('');
- }
這個要求我們對數組做些擴展,map將返回一個數組,然后我們再用join把它的元素串成字符。
實現4
- var getRandomColor = function(){
- return '#'+Math.floor(Math.random()*16777215).toString(16);
- }
這個實現非常逆天,雖然有點小bug。我們知道hex顏色值是從#000000到#ffffff,后面那六位數是16進制數,相當于"0x000000"到"0xffffff"。這實現的思路是將hex的***值ffffff先轉換為10進制,進行random后再轉換回16進制。我們看一下,如何得到16777215 這個數值的。
- <!doctype html>
- <meta charset="utf-8"/>
- <meta http-equiv="X-UA-Compatible" content="IE=8"/>
- <title>hex的***值</title>
- <script type="text/javascript" charset="utf-8">
- window.onload = function () {
- alert(parseInt("0xffffff",16).toString(10));
- };
- </script>
- <div id="text"></div>
運行代碼
實現5
- var getRandomColor = function(){
- return '#'+(Math.random()*0xffffff<<0).toString(16);
- }
基本實現4的改進,利用左移運算符把0xffffff轉化為整型。這樣就不用記16777215了。由于左移運算符的優先級比不上乘號,因此隨機后再左移,連Math.floor也不用了。
實現6
- var getRandomColor = function(){
- return '#'+(function(h){
- return new Array(7-h.length).join("0")+h
- })((Math.random()*0x1000000<<0).toString(16))
- }
修正上面版本的bug(無法生成純白色與hex位數不足問題)。0x1000000相當0xffffff+1,確保會抽選到0xffffff。在閉包里我們處理hex值不足6位的問題,直接在未位補零。
實現7
- var getRandomColor = function(){
- return '#'+('00000'+(Math.random()*0x1000000<<0).toString(16)).substr(-6);
- }
這次在前面補零,連遞歸檢測也省了。
上面版本生成顏色的范圍算是大而全,但隨之而來的問題是顏色不好看,于是實現8搞出來了。它生成的顏色相當鮮艷。
實現8
- var getRandomColor = function(){
- return "hsb(" + Math.random() + ", 1, 1)";
- }
實戰一下:
- <!doctype html>
- <html dir="ltr" lang="zh-CN">
- <head>
- <meta charset="utf-8"/>
- <meta http-equiv="X-UA-Compatible" content="IE=8">
- <title>初級餅圖</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 "hsb(" + Math.random() + ", 1, 1)";
- }
- window.onload = function () {
- var paper = Raphael("canvas", 700, 700);
- paper.rect(0, 0, 640, 480,10).attr({fill: "#F2F1D7",stroke: "none"});//設置畫板
- function drawSector(cx,cy,r,paper,oc,startAngle){
- var angleplus = 360 * oc / 100,//360度乘以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>初級餅圖</title>
- </head>
- <body>
- <p>初級餅圖</p>
- <div id="canvas"></div>
- </body>
- </html>
運行代碼
原文標題:javascript獲取隨機顏色
鏈接:http://www.cnblogs.com/rubylouvre/archive/2009/09/24/1572977.html
【編輯推薦】