做餅圖或標籤雲時常常需要大量顏色。途徑有兩條:準備一組精心挑選的候選色,或者隨機產生。當數量很多、或事先無法確定要幾種時,後者往往就是唯一出路。以下由淺入深整理七種實作,並說明各自的問題所在。
var getRandomColor = function () {
return '#' + (function (color) {
return (color += '0123456789abcdef'[Math.floor(Math.random() * 16)])
&& (color.length == 6) ? color : arguments.callee(color);
})('');
};
隨機取六個字元串接起來。閉包呼叫自身搭配三元運算子,讓程式碼變得相當內斂——初學者值得研究這種寫法,但實務上可讀性不佳,arguments.callee 在嚴格模式下也被禁用。
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 物件與色碼字串抽成參數,用第三個參數控制遞迴次數。局部變數的 lookups 較少,效能略優。
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 串成字串。這個版本要求我們自行擴充陣列(當年部分舊瀏覽器還不支援 map),今天已無必要——Array.prototype.map 是 ES5 標準,直接改擴充原型反而有污染風險。
var getRandomColor = function () {
return '#' + Math.floor(Math.random() * 16777215).toString(16);
};
這個寫法相當俐落,但有小 bug。十六進位色碼從 #000000 到 #ffffff,後六位其實就是 0x000000 到 0xffffff 這個範圍。程式先把 ffffff 轉成十進位、隨機取值後再轉回十六進位。那個 16777215 是怎麼來的?
parseInt("0xffffff", 16).toString(10) // → 16777215
問題在於:隨機結果若很小,toString(16) 只會產生一兩位數,組出的色碼不足六位而成為無效值。
var getRandomColor = function () {
return '#' + (Math.random() * 0xffffff << 0).toString(16);
};
改用左移運算子把浮點數轉為整數,就不必記 16777215 這個魔術數字了。由於位移運算的優先級低於乘號,寫成 Math.random() * 0xffffff << 0 剛好是先乘後位移,連 Math.floor 都能省下。位數不足的問題則依然存在。
var getRandomColor = function () {
return '#' + (function (h) {
return new Array(7 - h.length).join("0") + h;
})((Math.random() * 0x1000000 << 0).toString(16));
};
修正了上面兩個版本的 bug:一是無法產生純白色 #ffffff,二是位數不足。這裡把範圍改成 0x1000000(即 0xffffff + 1),確保能抽到最大值;並在閉包中把不足六位的部分補零。
var getRandomColor = function () {
return '#' + ('00000' + (Math.random() * 0x1000000 << 0).toString(16)).substr(-6);
};
把補零的邏輯簡化成「先湊滿五個零再取後六位」,連遞迴與條件判斷都省了。這是七個版本中最簡潔且正確的一個。
搭配 Raphael 這類向量繪圖函式庫,就能畫出每塊顏色都不同的圖表:
var getRandomColor = function () {
return '#' + ('00000' + (Math.random() * 0x1000000 << 0).toString(16)).substr(-6);
};
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,
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"].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);
}
};
要誠實說:隨機產生的顏色在視覺上往往很難看。均勻隨機取 RGB 會得到大量灰濁、飽和度過高或明度接近的顏色,相鄰的兩塊圖表很容易難以區分——這對需要傳達資訊的圖表來說是致命的問題。
比較好的策略有兩個。一是預先準備調和過的色盤,數量不夠時循環取用;二是在 HSL 色彩空間取隨機值,固定飽和度與明度、只讓色相變化,這樣產生的顏色會協調得多:
function randomHueColor(h, s, l) {
h = Math.floor(Math.random() * 360);
return `hsl(${h}, ${s || 65}%, ${l || 55}%)`;
}
另外別忘了無障礙:色相不同的顏色對色盲使用者可能完全無法區分,圖表應該同時搭配文字標籤或圖案差異,不要只依賴顏色傳遞資訊。