淺析利用Javascript獲取隨機(jī)顏色
本文將談到利用Javascript獲取隨機(jī)顏色,這里我們需要知道做Javascript獲取隨機(jī)顏色主要是在作圖時(shí)方便展示,希望大家能從本文獲得幫助。
在制作餅圖或標(biāo)簽云時(shí),我們通常需要很多顏色,方法有二。一是準(zhǔn)備一組漂亮的候選顏色,二是隨機(jī)生成顏色。在數(shù)量很多或不明確時(shí),我想后者就是唯一的出路了。谷歌了一下,整理如下,按由淺入深的順序排列。
實(shí)現(xiàn)1
- var getRandomColor = function(){
- return '#' +
- (function(color){
- return (color += '0123456789abcdef'[Math.floor(Math.random()*16)])
- && (color.length == 6) ? color : arguments.callee(color);
- })('');
- }
隨機(jī)生成6個(gè)字符然后再串到一起,閉包調(diào)用自身與三元運(yùn)算符讓程序變得內(nèi)斂,初心者應(yīng)該好好學(xué)習(xí)這種寫法。
實(shí)現(xiàn)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顏色值的字符串提取出來,并利用第三個(gè)參數(shù)來判斷是否還繼續(xù)調(diào)用自身。
實(shí)現(xiàn)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('');
- }
這個(gè)要求我們對數(shù)組做些擴(kuò)展,map將返回一個(gè)數(shù)組,然后我們再用join把它的元素串成字符。
實(shí)現(xiàn)4
- var getRandomColor = function(){
- return '#'+Math.floor(Math.random()*16777215).toString(16);
- }
這個(gè)實(shí)現(xiàn)非常逆天,雖然有點(diǎn)小bug。我們知道hex顏色值是從#000000到#ffffff,后面那六位數(shù)是16進(jìn)制數(shù),相當(dāng)于"0x000000"到"0xffffff"。這實(shí)現(xiàn)的思路是將hex的***值ffffff先轉(zhuǎn)換為10進(jìn)制,進(jìn)行random后再轉(zhuǎn)換回16進(jìn)制。我們看一下,如何得到16777215 這個(gè)數(shù)值的。
- <!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>
運(yùn)行代碼
實(shí)現(xiàn)5
- var getRandomColor = function(){
- return '#'+(Math.random()*0xffffff<<0).toString(16);
- }
基本實(shí)現(xiàn)4的改進(jìn),利用左移運(yùn)算符把0xffffff轉(zhuǎn)化為整型。這樣就不用記16777215了。由于左移運(yùn)算符的優(yōu)先級比不上乘號,因此隨機(jī)后再左移,連Math.floor也不用了。
實(shí)現(xiàn)6
- var getRandomColor = function(){
- return '#'+(function(h){
- return new Array(7-h.length).join("0")+h
- })((Math.random()*0x1000000<<0).toString(16))
- }
修正上面版本的bug(無法生成純白色與hex位數(shù)不足問題)。0x1000000相當(dāng)0xffffff+1,確保會(huì)抽選到0xffffff。在閉包里我們處理hex值不足6位的問題,直接在未位補(bǔ)零。
實(shí)現(xiàn)7
- var getRandomColor = function(){
- return '#'+('00000'+(Math.random()*0x1000000<<0).toString(16)).substr(-6);
- }
這次在前面補(bǔ)零,連遞歸檢測也省了。
上面版本生成顏色的范圍算是大而全,但隨之而來的問題是顏色不好看,于是實(shí)現(xiàn)8搞出來了。它生成的顏色相當(dāng)鮮艷。
實(shí)現(xiàn)8
- var getRandomColor = function(){
- return "hsb(" + Math.random() + ", 1, 1)";
- }
實(shí)戰(zhàn)一下:
- <!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"});//設(shè)置畫板
- 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>
運(yùn)行代碼
原文標(biāo)題:javascript獲取隨機(jī)顏色
鏈接:http://www.cnblogs.com/rubylouvre/archive/2009/09/24/1572977.html
【編輯推薦】