DIV CSS 佈局教程網

smipleChart:一個不依賴框架的輕量圖表類
編輯:關於JavaScript     

smipleChart 是一個用原生 JavaScript 寫成的輕量圖表類,同時兼容 SVG 與 VML,因此在老一點的 IE 上也能正常作畫。它支持折線圖、區域圖、柱狀圖、餅圖、多層餅圖等多種類型,自帶坐標軸、圖例、tooltip 與點擊切換顯示等操作。

由於在線編輯器會破壞代碼,作者另外提供了演示頁面:https://demo.jb51.net/chengxu/smipleChart.htm

一、整體結構

整個類被包在一個立即執行函數當中,通過特性檢測判斷當前環境支持 SVG 還是 VML:

(function (doc, undefined) {
  var win = this,
      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',
      ...
})(document);

同時掛載了 $、extend、each 三個基礎工具函數,讓後續代碼不必依賴任何第三方庫。

二、vector:對 SVG / VML 元素的統一封裝

為了抹平兩套渲染體系的差異,作者設計了一個 vector 類,用鏈式 API 完成元素創建與屬性設置:

win.vector = function () {};
win.vector.prototype = {
  $c: function (graphic, nodeName) {
    this.element = this[0] =
      doc.createElementNS('https://www.w3.org/2000/svg', nodeName);
    this.graphic = graphic;
    return this;
  },
  attr: function (hash, val) { /* 設置或讀取屬性 */ },
  css: function (hash) { /* 設置樣式,IE 下 opacity 換成 filter */ },
  on: function (eventName, handler) { /* 綁定事件 */ },
  appendTo: function (parent) { /* 插入到父容器 */ },
  addText: function (str) { /* 寫入文本節點 */ },
  setOpacity: function (v) { this.attr('fill-opacity', v); },
  toFront: function () { /* 提到最上層 */ },
  show: function () { /* 顯示 */ },
  hide: function () { /* 隱藏 */ }
};

如果檢測不到 SVG 支持,就動態創建 VML 命名空間與默認樣式,並覆寫 $c、on、addText、setOpacity 等方法:

if (!hasSVG) {
  doc.createStyleSheet().addRule(".vml",
    "behavior:url(#default#VML);display:inline-block;position:absolute;left:0px;top:0px");
  !doc.namespaces.vml && !+"\v1";
  doc.namespaces.add("vml", "urn:schemas-microsoft-com:vml");

  extend(vector.prototype, {
    $c: function (graphic, nodeName) { /* 用 createElement('<vml:...') */ },
    on: function (eventName, handler) { /* 改用 attachEvent */ },
    addText: function (txt) { /* 直接寫 innerHTML */ },
    setOpacity: function (v) { this.opacity.opacity = v; }
  });
}

三、初始流程

構造函數只做一件事:調用 init。init 裡的順序體現了整個繪製流程:

smipleChart.prototype = {
  init: function (container, options, width, height) {
    // 1. 計算尺寸、合併配置
    // 2. 建立 svg 或 div 容器
    // 3. 計算繪圖區參數
    this.getDrawArea()
        .createTooltip()   // 創建提示框
        .drawTitle()       // 畫主標題、副標題、側標題
        .drawPanel();      // 畫坐標盤子(餅圖除外)

    this.drawLegend(opts.legend.type);  // 畫圖例

    var type = {
      line: 'drawLine', area: 'drawArea', columns: 'drawColumns',
      pie: 'drawPie', pies: 'drawPies', segment: 'drawSegment'
    }[opts.charts.type];
    this[type]();
  }
};

四、幾個值得一看的細節

刻度計算

坐標軸刻度不是簡單等分,而是先在 [1, 2, 2.5, 5, 10] 這組「好看」的基數中找到合適的間隔,再把最小值和最大值向外擴展到整刻度,最後用剩餘的線數微調,讓圖形盡量居中且刻度易讀:

var arr = [1, 2, 2.5, 5, 10];
// 找到間隔屬於哪個數量級,再取最接近的一個作為 step
return { min: a, max: b, stf: v };

圖例可交互

點擊圖例可以顯示或隱藏對應的數據系列,被隱藏的圖例文字會變灰:

handle = function (i) {
  var g = self.mainGroup['chart' + i];
  if (g.show) {
    g.chart.hide();
    g.show = false;
    hasSVG ? this.attr({ fill: '#ccc' }) : this[0].style.color = '#ccc';
  } else {
    g.chart.show();
    g.show = true;
    hasSVG ? this.attr({ fill: '#000' }) : this[0].style.color = '#000';
  }
};

空數據的處理

折線圖和區域圖都支持 null 值:遇到空數據時在 path 中插入一個 M(move)指令來斷開線段,而不是錯誤地連成直線。

餅圖的「分離」效果

每個扇區預先算好一個位移向量,點擊時在 translate 上切換,實現扇區外移的效果:

moveDisplacement = ((x - rx) * 8 / len) + ',' + ((y - ry) * 8 / len);

五、調用示例

window.onload = function () {
  var config = {
    charts: { type: 'line', radius: 150, panel: 'x', style: { fontSize: '12px' } },
    title:    { text: '線性圖標', y: 10 },
    subTitle: { text: '線性圖標副標題', y: 35 },
    legend:   { enable: true, type: 'lateral', pos: [10, 10] },
    yUnit:    { text: '線性圖標側標題', x: 20 },
    xUnit:    { units: ['一月', '二月', '三月', '十二月'] },
    chartData: [
      { name: 'xcv',   color: '#4572A7', data: [-18, 45, -38, 29, 95, -45, 77] },
      { name: 'frfr',  color: '#AA4643', data: [-44, 12, 78, -100, 13, 4, -56] },
      { name: 'AAAAA', color: '#89A54E', data: [null, 78, 83, null, 22, -78, 2] }
    ]
  };

  new smipleChart($('line'), config);

  config.charts.type = 'area';
  new smipleChart($('area'), config);

  config.charts.type = 'columns';
  new smipleChart($('zhu'), config);

  config.charts.type = 'pie';
  new smipleChart($('pie'), config);
};

可以看到配置對象是復用的,只改動 charts.type 與標題文字,就能在同一份數據上切換出多種圖表。

小結

這個類的價值主要在於示範了幾件事:如何用一層薄封裝抹平 SVG 與 VML 的差異、如何計算美觀的坐標刻度、如何用 path 表達斷裂的數據序列。以今天的眼光看,它不會是你項目的首選(現代方案如 ECharts、Chart.js 功能更完整),但作為理解圖表繪製原理的讀本,依然值得一讀。

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