萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

VML 實現餅圖的 JavaScript 類封裝:IE 專有向量圖形技術深度解析

前言

VML (Vector Markup Language) 是微軟在 IE5+ 實現的向量圖形標準,**僅支援 Internet Explorer**(現代 Edge/Chrome/Firefox 不支援)。雖然已被 SVG/Canvas 取代,但在維護極舊 IE 專案時仍可能遇到。本文完整呈現一個基於 VML 的餅圖 JS 類封裝源碼,並深度解析其核心繪圖邏輯、座標系統、漸層/陰影/圖例實現。

一、VML 環境準備

<html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">
<head>
<style>
v\:* { behavior: url(#default#VML); }
o\:* { behavior: url(#default#VML); }
.shape { behavior: url(#default#VML); }
</style>
</head>
  • xmlns:v、xmlns:o:宣告 VML/Office 命名空間
  • behavior: url(#default#VML):關鍵,啟用 IE 的 VML 渲染引擎

二、VMLPie 類完整源碼(含註釋)

/**
 * VML 餅圖類
 * @param {HTMLElement} pContainer 容器元素
 * @param {string} pWidth 寬度 (如 "400px")
 * @param {string} pHeight 高度 (如 "250px")
 * @param {string} pCaption 標題文字
 */
function VMLPie(pContainer, pWidth, pHeight, pCaption) {
    this.Container = pContainer;
    this.Width = pWidth || "400px";
    this.Height = pHeight || "250px";
    this.Caption = pCaption || "VML Chart";
    this.backgroundColor = "";
    this.Shadow = false;
    this.BorderWidth = 0;
    this.BorderColor = null;
    this.all = []; // 資料項陣列 [{Name, Value, TooltipText}, ...]

    // 隨機顏色生成器
    this.RandColor = function() {
        return "rgb(" + 
            parseInt(Math.random() * 255) + "," + 
            parseInt(Math.random() * 255) + "," + 
            parseInt(Math.random() * 255) + ")";
    };
    this.VMLObject = null;
}

/**
 * 添加資料項
 * @param {string} name 名稱
 * @param {number} value 數值
 * @param {string} tooltip 提示文字
 */
VMLPie.prototype.AddItem = function(name, value, tooltip) {
    this.all.push({
        Name: name,
        Value: value,
        TooltipText: tooltip || ""
    });
};

/**
 * 核心繪製入口
 */
VMLPie.prototype.Draw = function() {
    // 1. 建立群組容器
    var o = document.createElement("v:group");
    o.style.width = this.Width;
    o.style.height = this.Height;
    o.coordsize = "21600,21600"; // VML 座標系統:21600 = 1 英吋 (1440 twips/inch * 15)

    // 2. 背景矩形層
    var vRect = document.createElement("v:rect");
    vRect.style.width = "21600px";
    vRect.style.height = "21600px";
    o.appendChild(vRect);

    // 3. 標題文字框
    var vCaption = document.createElement("v:textbox");
    vCaption.style.fontSize = "24px";
    vCaption.style.height = "24px";
    vCaption.style.fontWeight = "bold";
    vCaption.innerHTML = this.Caption;
    vCaption.style.textAlign = "center";
    vRect.appendChild(vCaption);

    // 4. 邊框/背景/陰影樣式
    if (this.BorderWidth) vRect.strokeweight = this.BorderWidth;
    if (this.BorderColor) vRect.strokecolor = this.BorderColor;
    if (this.backgroundColor) vRect.fillcolor = this.backgroundColor;
    if (this.Shadow) {
        var vShadow = document.createElement("v:shadow");
        vShadow.on = "t";
        vShadow.type = "single";
        vShadow.color = "graytext";
        vShadow.offset = "4px,4px";
        vRect.appendChild(vShadow);
    }

    this.VMLObject = o;
    this.Container.appendChild(o);

    // 5. 繪製底部橢圓(餅圖基底,含 3D 擠壓效果)
    var oOval = document.createElement("v:oval");
    oOval.style.width = "15000px";
    oOval.style.height = "14000px";
    oOval.style.top = "4000px";
    oOval.style.left = "1000px";
    oOval.fillcolor = "#d5dbfb";

    // 3D 擠壓與漸層填充 (VML 特有)
    var formatStyle = 
        '<v:fill rotate="t" angle="-135" focus="100%" type="gradient"/>' +
        '<o:extrusion v:ext="view" backdepth="1in" on="t" ' +
        'viewpoint="0,34.72222mm" viewpointorigin="0,.5" ' +
        'skewangle="90" lightposition="-50000" lightposition2="50000" type="perspective"/>';
    oOval.innerHTML = formatStyle;
    o.appendChild(oOval);

    // 6. 繪製餅圖扇區 + 圖例
    this.CreatePie(o);
};

/**
 * 繪製餅圖扇區與圖例
 */
VMLPie.prototype.CreatePie = function(vGroup) {
    // VML 角度單位:1 度 = 2^16 = 65536
    var mX = Math.pow(2, 16) * 360; // 360 度對應的單位總數

    var vTotal = 0;
    this.all.forEach(item => vTotal += item.Value);

    var startAngle = 0;
    var prePieAngle = 0;

    // --- 圖例區域 ---
    var objLegendRect = document.createElement("v:rect");
    objLegendRect.style.left = "17000px";
    objLegendRect.style.top = "4000px";
    objLegendRect.style.width = "4000px";
    objLegendRect.style.height = "12000px";
    objLegendRect.fillcolor = "#e6e6e6";
    objLegendRect.strokeweight = "1px";

    var objLegendTable = document.createElement("table");
    objLegendTable.cellPadding = 0;
    objLegendTable.cellSpacing = 3;
    objLegendTable.width = "100%";

    // 總數行
    var objRow = objLegendTable.insertRow();
    var objCell = objRow.insertCell();
    objCell.colSpan = "2";
    objCell.style.backgroundColor = "black";
    objCell.style.color = "window";
    objCell.style.padding = "5px";
    objCell.innerText = "總數:" + vTotal;

    // 各項顏色色塊 + 名稱 + 數值 + 百分比
    this.all.forEach(item => {
        var row = objLegendTable.insertRow();
        var colorCell = row.insertCell();
        colorCell.style.width = "20px";
        colorCell.style.backgroundColor = item.Color || this.RandColor(); // 需預先指定或隨機
        colorCell.innerHTML = " ";
        var textCell = row.insertCell();
        textCell.innerText = item.Name + ": " + item.Value + " (" + (item.Value/vTotal*100).toFixed(1) + "%)";
    });

    var vTextbox = document.createElement("v:textbox");
    vTextbox.appendChild(objLegendTable);
    objLegendRect.appendChild(vTextbox);

    // 圖例陰影
    var vShadow = document.createElement("v:shadow");
    vShadow.on = "t"; vShadow.type = "single"; vShadow.color = "graytext"; vShadow.offset = "2px,2px";
    objLegendRect.appendChild(vShadow);

    vGroup.appendChild(objLegendRect);

    // --- 繪製每個扇區 ---
    this.all.forEach((item, i) => {
        var vPieEl = document.createElement("v:shape");
        vPieEl.style.width = "15000px";
        vPieEl.style.height = "14000px";
        vPieEl.style.top = "4000px";
        vPieEl.style.left = "1000px";
        vPieEl.coordsize = "1500,1400"; // 子座標系統
        vPieEl.strokecolor = "white";
        vPieEl.id = document.uniqueID; // IE 獨有唯一 ID

        // 計算角度
        var pieAngle = item.Value / vTotal;
        startAngle += prePieAngle;
        prePieAngle = pieAngle;
        var endAngle = pieAngle;

        // VML 路徑:M x y AE x y w h startAngle endAngle
        // AE = 橢圓弧 (Arc Ellipse)
        vPieEl.path = "M 750 700 AE 750 700 750 700 " + 
            parseInt(mX * startAngle) + " " + parseInt(mX * endAngle) + " xe";

        // 滑鼠懸停提示
        vPieEl.title = item.Name + "\n所占比例:" + (endAngle * 100).toFixed(1) + "%\n詳細描述:" + item.TooltipText;

        // 填充顏色
        var fillColor = item.Color || this.RandColor();
        vPieEl.fillcolor = fillColor;
        // 同步更新圖例色塊 (需保存引用)
        // item._colorCell.style.backgroundColor = fillColor;

        vGroup.appendChild(vPieEl);
    });
};

// === 使用範例 ===
/*
var chart = new VMLPie(document.body, "500px", "400px", "銷售占比圖");
chart.AddItem("產品 A", 120, "核心產品線");
chart.AddItem("產品 B", 80, "成長中");
chart.AddItem("產品 C", 50, "維護模式");
chart.AddItem("其他", 30, "雜項");
chart.Draw();
*/

三、VML 核心技術點深度解析

1. 座標系統:21600 = 1 英吋

VML 使用 **twip (twentieth of a point)** 作為內部單位:

  • 1 英吋 = 72 點 = 1440 twip
  • VML coordsize 預設 21600 = 15 英吋 (1440 × 15)
  • 所有位置、尺寸、角度均基於此單位計算

2. 扇區路徑語法:AE (Arc Ellipse)

path = "M cx cy AE cx cy rx ry startAngle endAngle xe"
// M: 移動到中心點
// AE: 繪製橢圓弧
//   cx, cy: 圓心
//   rx, ry: x/y 半徑
//   startAngle, endAngle: 起始/結束角度 (單位: 1/65536 度)
// xe: 結束路徑

3. 3D 效果:o:extrusion

  • type="perspective":透視投影
  • skewangle="90":傾斜角度
  • viewpoint:觀察點位置
  • lightposition:光源位置
  • backdepth:擠壓深度

4. 漸層填充:v:fill type="gradient"

  • angle:漸層角度
  • focus:焦點位置
  • rotate="t":隨形狀旋轉

四、現代替代方案(強烈建議)

**VML 已死,請勿在新專案使用。** 現代圖表庫均基於 SVG/Canvas,支援所有瀏覽器:

類型推薦庫特點
SVG 基礎D3.js, Snap.svg底層控制力最強、資料驅動文檔
圖表專用Chart.js, ECharts, Highcharts, AntV/G2開箱即用、響應式、動畫豐富、無障礙
Canvas 高效能uCharts, F2移動端優化、小程序支援
React/Vue 生態Recharts, Visx, Vue-ECharts組件化、TypeScript 友好

最簡 SVG 餅圖示例 (無依賴)

<svg width="200" height="200" viewBox="0 0 100 100">
    <path d="M50,50 L50,0 A50,50 0 0,1 90,30 Z" fill="#3498db" />
    <path d="M50,50 L90,30 A50,50 0 0,1 20,80 Z" fill="#e74c3c" />
    <path d="M50,50 L20,80 A50,50 0 0,1 50,0 Z" fill="#2ecc71" />
</svg>

結語

VML 是瀏覽器戰爭時期的產物,其coordsize、AE 路徑、o:extrusion 3D 擠壓等設計極具特色,理解它有助於掌握向量圖形底層原理。但**生產環境請毫不猶豫選擇 SVG/Canvas 生態**。若必須維護 IE8- 專案,可考慮 ExCanvas (將 Canvas API 轉譯為 VML) 或 Raphaël (統一 SVG/VML API) 等橋接庫,而非手寫 VML 代碼。

copyright © 萬盛學電腦網 all rights reserved