在 Canvas、SVG 和各種圖表庫普及之前,前端要畫圖只有一條路:VML。這個老示例示範了兩件事——如何用 VML 拼出一張圓餅圖,以及如何用 JavaScript 動態生成柱狀條形圖。今天看來技術已過時,但它把「數據到圖形」的映射講得很透。
VML 是 IE 特有的矢量標記語言,靠 v:group、v:shape、v:rect 等標籤描述圖形。要在頁面裡啟用它,需要兩步聲明:
<xml:namespace prefix="v"/>
<style>
v:* { behavior: url(#default#VML) }
</style>
接著用一個 v:group 當畫布,裡面每塊扇區都是一個 v:shape,路徑由 path 屬性描述。所謂「畫圓餅」,其實是畫橢圓弧再閉合到圓心:
<v:group style='height:324pt;width:432pt' coordsize="4320,3240">
<!-- 白色紙面加一層簡單投影 -->
<v:rect style='width:4320;height:3240' fillcolor="white">
<v:shadow on="true" offset="4pt,3pt" color="silver" />
</v:rect>
<v:shape style='position:absolute;width:4320;height:3240'
strokeweight=0.5pt fillcolor="#DBDBED"
path="M 2250 1590 AE 2250 1590 791 791 -3538944 9437184 X E" />
<v:shape style='position:absolute;width:4320;height:3240'
strokecolor="#000000" strokeweight=0.7pt>
<v:stroke joinstyle=round endcap=round />
<v:fill on="false" />
<v:path v=" M 3115 1309 L 2927 1370 E " />
</v:shape>
<!-- 其餘扇區(Two: 18、Three: 13、Four: 9、Five: 5)
結構完全相同,僅 fillcolor 與 path 的起止角度不同 -->
</v:group>
路徑裡的 AE 表示橢圓弧,後面跟著圓心座標、半徑以及起止角度(單位是 1/65536 度,所以會出現 -3538944 這種數字)。文字標籤則用絕對定位的段落疊上去,例如 <p class=Chart style='position:absolute;left:315.9pt;top:127.3pt;'>One: 30</p>。可以看出,這一切都是手工算好座標硬寫出來的,毫無「數據驅動」可言。
下半部分的思路就現代得多:用隨機數當數據,用表格單元格的背景色當柱體,動態 document.write 輸出。
function displayTitle(title) {
document.write("<center><i>" + title + "</i></center><br>");
}
function generateRandomNumber(num) {
return Math.round(Math.random() * (num - 1)) + 1;
}
function plottablehead(val) {
document.writeln("<table border=0 bgcolor=black width=10 height=10 cellpadding=0 cellspacing=0>");
document.write("<tr> <i>" + val + "</i>");
}
function plottabletail() {
document.write("</tr></table><br>");
}
// 循環輸出 d 個帶指定顏色的單元格,d 就是柱高
function plotcolor(d, clr) {
for (i = 1; i <= d; i++) {
document.write("<td bgcolor = " + clr + "> </td>");
}
}
function setColor(foreground, background) {
document.fgColor = foreground;
document.bgColor = background;
}
setColor("orange", "black");
a = generateRandomNumber(50); plottablehead(a); plotcolor(a, "red"); plottabletail();
a = generateRandomNumber(50); plottablehead(a); plotcolor(a, "blue"); plottabletail();
a = generateRandomNumber(50); plottablehead(a); plotcolor(a, "green"); plottabletail();
a = generateRandomNumber(50); plottablehead(a); plotcolor(a, "yellow"); plottabletail();
a = generateRandomNumber(50); plottablehead(a); plotcolor(a, "gray"); plottabletail();
a = generateRandomNumber(50); plottablehead(a); plotcolor(a, "midnightblue"); plottabletail();
兩種畫法對比鮮明:VML 靠座標堆砌,本質是「排版」;JS + 表格靠循環,本質是「渲染」。而真正讓柱狀圖成立的關鍵,是 plotcolor 裡那個把「數值 d」直接當成「循環次數」的映射——數據有多大,格子就鋪多少個。這正是所有圖表庫最初的骨架。