要在網頁上畫圖表,早期只有兩條路:要嘛自己用一堆 div 拼,要嘛掛一個龐大的圖表庫。smipleChart 走的是另一條——直接操作向量繪圖元素,支援 SVG 的瀏覽器就用 SVG,不支援的舊版 IE 就自動切到 VML,同一份程式碼兩邊都能跑。內建折線圖、區域圖、柱狀圖、條形圖、圓餅圖、多層圓餅圖與分段堆疊圖,並附上限表、tooltip 與可切換顯示的圖例。
這是那個年代的標準難題。SVG 是真正的 XML 命名空間,元素要用 createElementNS 建立、用 setAttribute 設定;VML 則是 IE 私有格式,元素名稱要寫成 <vml:shape>,靠 behavior:url(#default#VML) 生效,屬性名稱也不大一樣(strokeWeight 對 stroke-width、filled 對 fill)。程式開頭先做一次能力偵測,把結果記在 hasSVG:
var hasSVG = win.SVGAngle ||
doc.implementation.hasFeature(
"https://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1"),
isIE = /msie/i.test(navigator.userAgent) && !win.opera,
path = hasSVG ? 'd' : 'path',
seal = hasSVG ? 'z' : 'e';
接著用一個 vector 包裝層把差異吸收掉:$c 建立節點、attr 設定屬性、css 設定樣式(IE 的 opacity 要轉成 alpha filter)、appendTo 掛到父層、on 綁事件、toFront 提到最上層。等到 !hasSVG 時,再用 extend 把 $c、addText、setSize、setOpacity 這幾個方法覆寫成 VML 版本,並補上 VML 的命名空間與樣式表:
if(!hasSVG){
doc.createStyleSheet().addRule(".vml",
"behavior:url(#default#VML);display:inline-block;position:absolute;left:0px;top:0px");
doc.namespaces.add("vml", "urn:schemas-microsoft-com:vml");
extend(vector.prototype, {
$c : function(graphic, nodeName){
var name = nodeName || 'shape';
this.element = this[0] = (name === 'div' || name === 'span')
? doc.createElement(name)
: doc.createElement('<vml:' + name + ' class="vml">');
this.graphic = graphic;
return this;
},
setSize : function(v){ this[0].strokeWeight = v; return this; },
setOpacity : function(v){ this.opacity.opacity = v; return this; }
});
}
這層包裝是整份程式最值得學的地方:把環境差異集中在最底層,上面的繪圖邏輯就能寫成一份。
如果直接拿最大值除以十當刻度間距,很容易出現 3.7、11.2 這種難看的數字。這裡的 xx() 函式先把基準序列定為 [1, 2, 2.5, 5, 10],依資料範圍放大或縮小倍率,再挑出第一個大於目標間距的值作為刻度,最後把起點與終點吸附到刻度的整數倍上,還會在空間有餘時把座標調成 10 的倍數,讓標籤更好讀。
function xx(a, b, lineNum){
var t = 1000, arr = [1, 2, 2.5, 5, 10], c = 1, v,
stf = ((b * t - a * t) / lineNum) / t;
if(stf < arr[0]){
while(stf < arr[0]){ c = c * 10; arr[0] = arr[0] / c; }
each([1, 2, 2.5, 5, 10], function(i, o){ arr[i] = o / c; });
}else if(stf > arr[4]){
while(stf > arr[4]){ c = c * 10; arr[4] = arr[4] * c; }
each([1, 2, 2.5, 5, 10], function(i, o){ arr[i] = o * c; });
}
each(arr, function(i, o){
if(stf <= o){ v = o; return false; }
});
a = (a * t + ba) / t; // 起點吸附
b = (b * t + (b % v === 0 ? 0 : (v - b % v)) * t) / t;
return { min:a, max:b, stf:v };
}
為了避免浮點誤差,程式中大量使用「先乘 1000 取整、算完再除回來」的技巧。這也是作者文末提到的痛點:JavaScript 的浮點精度問題確實不好根治,與其追求完美,不如在顯示與比較的環節統一做一次 toFixed 或整數化。
所有圖形最後都收斂到 baseDraw 這組方法:rect(圓角矩形)、path(路徑)、circle、square、triangle、diamond、text/span(文字)、pie(扇形)。SVG 版用 <path d="M ... L ... A ... Z"> 描述一切,VML 版則改用 wa(順時針弧)、at(弧到)、x(結束路徑)這些指令,並以 coordsize 對應 viewBox 的概念。
path : function(o, config){
var set = {};
set['stroke-width'] = config.border;
set.stroke = config.borderColor || '#C0C0C0';
set.fill = config.isfill ? config.fillColor : 'none';
set.d = config.path;
config.opacity && (set['fill-opacity'] = config.opacity);
return o.createElement('path').attr(set);
},
pie : function(o, config){
var area = o.opts.area, r = config.r,
rx = area.centerX, ry = area.centerY,
s = config.s, e = config.e - 0.000001,
longArc = e - s < Math.PI ? 0 : 1,
path = [
'M', rx + r * mathCos(s), ry + r * mathSin(s),
'A', r, r, 0, longArc, 1, rx + r * mathCos(e), ry + r * mathSin(e),
'L', rx + config.innerR * mathCos(e), ry + config.innerR * mathSin(e),
'A', config.innerR, config.innerR, 0, longArc, 0,
rx + config.innerR * mathCos(s), ry + config.innerR * mathSin(s),
'Z'
];
return o.baseDraw.path(o, {
border:1, isfill:true, fillColor: config.config.color, opacity:1, path: path
});
}
圓餅/環圈的做法很巧妙:外圈用一個 A 指令畫弧,內圈再用反向的 A 指令繞回起點。當 innerR 為 0 就是圓餅圖,大於 0 就自動變成甜甜圈圖,多層圓餅圖也是靠不同 innerR 一層層堆出來的。
建構子只吃兩個參數:容器元素與設定物件。改變 charts.type 就能換圖表類型,改 chartData 就能換資料,標題、副標題、側標題、圖例位置與 Y 軸線條數量都是設定項。
window.onload = function(){
var config = {
charts : {
type : 'line', // line / area / columns / pie / pies / segment
radius : 150,
panel : 'x', // x 為橫向(含雙向)座標,y 為縱向條形
style : { fontSize: '12px' }
},
title : { text:'線性圖表', y:10, style:{ color:'black', fontSize:'16px' } },
subTitle : { text:'線性圖表副標題', y:35, style:{ color:'#111', fontSize:'12px' } },
yUnit : { text:'線性圖表側標題', x:20, lineNum:10 },
legend : { enable:true, type:'lateral', pos:[10, 10] },
xUnit : { units: ['一月','二月','三月','四月','五月','六月',
'七月','八月','九月','十月','十一月','十二月'] },
chartData: [
{ name:'xcv', color:'#4572A7', dotType:'square', data:[ 44,-12,-78,100,-13,-4,-26,34] },
{ name:'frfr', color:'#AA4643', dotType:'triangle', data:[-44, 12, 78,-100, 13, 4,-56,-34] },
{ name:'AAAAA', color:'#89A54E', dotType:'diamond', data:[null, 78, 83,null, 22,-78, 2, 44] },
{ name:'BBBB', color:'#80699B', data:[null, 58, 35,null, 52, 47,26,-55] }
]
};
new smipleChart($$('line'), config);
config.charts.type = 'area';
config.title.text = '區域圖表';
new smipleChart($$('area'), config);
config.charts.type = 'columns';
config.title.text = '柱狀圖表';
new smipleChart($$('zhu'), config);
config.charts.panel = 'y'; // 轉成橫向條形圖
new smipleChart($$('zhu1'), config);
config.charts.type = 'pie';
config.legend.type = 'lengthwise'; // 圖例改縱排
config.legend.pos = [680, 30];
new smipleChart($$('pie'), config);
config.charts.type = 'pies'; // 多層圓餅
config.legend.type = 'lateral';
config.legend.pos = [290, 400];
new smipleChart($$('pies'), config);
config.charts.type = 'segment'; // 分段堆疊
config.legend.pos = [10, 10];
new smipleChart($$('segmentx'), config);
};
容器只是一塊有尺寸的空 div,圖表會自己撐滿:
<div id='line' class="cc"></div>
<div id='area' class="cc"></div>
<div id='zhu' class="cc"></div>
<style>
.cc { height:450px; width:800px; border:1px solid #999; position:relative; margin:20px; }
</style>
有大量圖表時的延遲繪製:頁面若同時放十幾張圖,一次全部同步繪製會讓畫面卡住。這裡的做法是把每個實例放進 smipleChart.list,先顯示 loading 圖片,再用 setTimeout 排隊,一張畫完才接著畫下一張(lazyLoad)。
圖例可互動:點擊圖例會切換對應資料的顯示,並把色塊文字變灰。分段圖因為需要重新計算堆疊,切換時會先清空該組節點再重畫。
tooltip 有位移動畫:第二次之後的 tooltip 不是瞬間跳位,而是用一個簡易的緩動函式在 5 個單位時間內插值移動過去。
折線圖支援缺值:資料中的 null 會讓 path 插入一個新的 M(move to)指令,於是折線斷開而不是把點連成一條歪線,這對「某些月份沒有數據」的情境很實用。
作者自陳「水平有限,難免問題多多」,其實這份程式裡有不少值得借鏡的設計:能力偵測加包裝層吸收跨環境差異、把刻度計算獨立成純函式、以設定物件驅動多種圖表、用佇列避免大量圖表阻塞主執行緒。缺點同樣明顯——手工操作 DOM 與屬性字串、部分邊界條件(例如全為 null 的資料列)處理不夠嚴謹、浮點誤差靠大量 ×1000 硬扛。
若要在新專案裡做圖表,成熟方案(SVG 為主、Canvas 或 WebGL 加速)在效能、無障礙與互動上已經領先許多。但如果你想知道「圖表是怎麼被畫出來的」,從這份把 SVG 與 VML 都親手寫過一遍的程式入手,會比直接呼叫 API 得到更多。理解路徑指令、座標系換算與刻度吸附之後,換任何工具都能很快上手。