DIV CSS 佈局教程網

用 VML 打造餅圖:JavaScript 類別封裝完整解析
編輯:JavaScript綜合知識     

在 Canvas 與 SVG 普及之前,VML(Vector Markup Language)是 Internet Explorer 用來在頁面上繪製向量圖的方案。本文示範如何把一個餅圖的繪製邏輯封裝成可重複使用的 JavaScript 類別,包含資料新增、圖例互動、陰影與縮放等能力。

先建立 VML 命名空間並掛上行為樣式:

<html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">
<head>
<title>VML 餅圖</title>
<STYLE>
v\:* { BEHAVIOR: url(#default#VML) }
o\:* { BEHAVIOR: url(#default#VML) }
.shape { BEHAVIOR: url(#default#VML) }
</STYLE>

建構函式:屬性集中管理

把可調參數都掛在 this 上,外部只要改屬性再呼叫 Draw() 即可:

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 = new Array();
  this.VMLObject = null;
  // 隨機配色
  this.RandColor = function(){
    return "rgb(" + parseInt(Math.random() * 255) + "," +
      parseInt(Math.random() * 255) + "," +
      parseInt(Math.random() * 255) + ")";
  };
}

Draw():畫出外框、標題與圓形底層

VMLPie.prototype.Draw = function(){
  // 畫外框
  var o = document.createElement("v:group");
  o.style.width = this.Width;
  o.style.height = this.Height;
  o.coordsize = "21600,21600";

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

  // 標題
  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);

  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);

  // 內部圓
  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";

  var formatStyle = '<v:fill rotate="t" angle="-135" focus="100%" type="gradient"/>';
  formatStyle += '<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);
  this.CreatePie(o);
}

CreatePie():角度換算與扇形繪製

VML 的角度單位並不是度數,而是 2^16 × 度數。因此程式碼開頭先把一整圈換算成 Math.pow(2,16) * 360,後續再以「占比 × 整圈」得到每塊扇形的起訖角度。

VMLPie.prototype.CreatePie = function(vGroup){
  var mX = Math.pow(2, 16) * 360;
  // AE x y width height startangle endangle
  // x y 為圓心位置;width height 為形狀大小
  // 角度計算方式:2^16 * 度數

  var vTotal = 0, startAngle = 0, endAngle = 0, pieAngle = 0, prePieAngle = 0;
  for(var i = 0; i < this.all.length; i++){
    vTotal += this.all[i].Value;
  }

  // 圖例容器
  var objLegendRect = document.createElement("v:rect");
  var objLegendTable = document.createElement("table");
  objLegendTable.cellPadding = 0;
  objLegendTable.cellSpacing = 3;
  objLegendTable.width = "100%";
  with(objLegendRect){
    style.left = "17000px";
    style.top = "4000px";
    style.width = "4000px";
    style.height = "12000px";
    fillcolor = "#e6e6e6";
    strokeweight = "1px";
  }
  var objRow = objLegendTable.insertRow();
  var objCell = objRow.insertCell();
  objCell.colSpan = "2";
  objCell.style.backgroundColor = "black";
  objCell.style.padding = "5px";
  objCell.style.color = "window";
  objCell.style.font = "caption";
  objCell.innerText = "總數:" + vTotal;

  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);

  // 依序畫出各扇形
  for(var i = 0; i < this.all.length; i++){
    var vPieEl = document.createElement("v:shape");
    var vPieId = document.uniqueID;
    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 = vPieId;

    pieAngle = this.all[i].Value / vTotal;
    startAngle += prePieAngle;
    prePieAngle = pieAngle;
    endAngle = pieAngle;

    vPieEl.path = "M 750 700 AE 750 700 750 700 " +
      parseInt(mX * startAngle) + " " + parseInt(mX * endAngle) + " xe";
    vPieEl.title = this.all[i].Name + "\n所占比例:" + endAngle * 100 +
      "%\n詳細描述:" + this.all[i].TooltipText;

    // 漸層填色,角度依扇形位置調整
    var objFill = document.createElement("v:fill");
    objFill.rotate = "t";
    objFill.focus = "100%";
    objFill.type = "gradient";
    objFill.angle = parseInt(360 * (startAngle + endAngle / 2));
    vPieEl.appendChild(objFill);

    var vColor = this.RandColor();
    vPieEl.fillcolor = vColor;

    // 圖例項目
    objRow = objLegendTable.insertRow();
    objRow.style.height = "16px";
    var objColor = objRow.insertCell();
    objColor.style.backgroundColor = vColor;
    objColor.style.width = "16px";
    objColor.PieElement = vPieId;
    objColor.attachEvent("onmouseover", LegendMouseOverEvent);
    objColor.attachEvent("onmouseout", LegendMouseOutEvent);

    objCell = objRow.insertCell();
    objCell.style.font = "icon";
    objCell.style.padding = "3px";
    objCell.innerText = this.all[i].Name + ":" + this.all[i].Value;

    vGroup.appendChild(vPieEl);
  }
}

資料操作與縮放

VMLPie.prototype.Zoom = function (iValue){
  var vX = 21600, vY = 21600;
  this.VMLObject.coordsize = parseInt(vX / iValue) + "," + parseInt(vY / iValue);
}

VMLPie.prototype.AddData = function(sName, sValue, sTooltipText){
  var oData = new Object();
  oData.Name = sName;
  oData.Value = sValue;
  oData.TooltipText = sTooltipText;
  this.all[this.all.length] = oData;
}

VMLPie.prototype.Clear = function(){
  this.all.length = 0;
}

function LegendMouseOverEvent(){
  var eSrc = window.event.srcElement;
  eSrc.border = "1px solid black";
}
function LegendMouseOutEvent(){
  var eSrc = window.event.srcElement;
  eSrc.border = "";
}

呼叫方式

var objPie = null;
function DrawPie(){
  objPie = new VMLPie(document.body, "600px", "450px", "人口統計圖");
  objPie.backgroundColor = "#ffffff";
  objPie.Shadow = true;

  objPie.AddData("北京", 10, "北京的人口");
  objPie.AddData("上海", 52, "上海的固定人口");
  objPie.AddData("天津", 30, "天津的外地人口");
  objPie.AddData("西安", 58, "西安城市人口");
  objPie.AddData("武漢", 30, "武漢的外地人口");
  objPie.AddData("重慶", 58, "重慶城市人口");
  objPie.Draw();
}

最後搭配一個下拉選單即可控制縮放(原始範例另附一組 <v:shapetype> 定義,用於自訂 tooltip 外觀的向量路徑與公式):

<select id="zoom" onchange="objPie.Zoom(this.value)">
  <option value="0.2" selected>20%</option>
  <option value="0.5">50%</option>
  <option value="1">原始大小</option>
  <option value="2">200%</option>
  <option value="4">400%</option>
</select>
<body onload="DrawPie()">

現在還能這樣寫嗎?

這份程式碼有相當濃厚的時代痕跡:document.createElement("v:shape")、attachEvent、window.event.srcElement、with 語句都只存在於舊版 IE,VML 本身也早已被 SVG 取代。它真正的價值在於示範「用原型方法把繪圖邏輯封裝成類別」這個思路——同樣的分層方式,套到 Canvas 或 SVG 上依然成立:AddData 負責資料、Draw 負責骨架、Zoom 負責視圖變換,職責切得乾淨。若今天要畫餅圖,直接用 SVG path 或 ECharts、Chart.js 這類現成套件會省力得多。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved