DIV CSS 佈局教程網

RequireJS 實作簡易繪圖程式:用模組化拆分 Canvas 圖形邏輯
編輯:關於JavaScript     

前言

RequireJS 的出現讓前端程式碼模組化變得容易。當專案越來越大、程式碼越來越多時,模組化能讓結構更清晰——不僅開發時思路清楚,後期維護也更省力。本文以一個瀏覽器端的簡易繪圖程式為例,說明如何用 RequireJS 組織 Canvas 相關的程式碼。

若對 RequireJS 還不熟,可先參考 RequireJS 學習筆記:https://blog.csdn.net/yubo_725/article/details/52913853

專案結構

index.html 是主頁,js 目錄存放所有 js 檔。js/app 是自訂的模組檔,js/lib 用來放第三方框架(如 jQuery),js/main.js 是 RequireJS 的設定檔,js/require.min.js 則是框架本身。

一、設定 RequireJS

 require.config({
  baseUrl: 'js/lib',
  paths: {
    app: '../app'
  }
})

這裡把根目錄設為 js/lib,並註冊一個名為 app 的路徑指向 ../app,也就是 js/app。之後所有自訂模組都能用 app/point 這樣的簡寫來引用。

二、撰寫各模組

point.js —— 點

 /** 點 */
define(function() {
  return function(x, y) {
    this.x = x;
    this.y = y;
    this.equals = function(point) {
      return this.x === point.x && this.y === point.y;
    };
  };
})

用 define 定義模組,回呼函數中回傳一個類,該類有 x、y 兩個參數與一個 equals 方法用於比較兩點是否相同。使用方式:

 require(['app/point'], function(Point) {
  // 新建一個點類的物件
  var point = new Point(3, 5);
})

要注意 require() 的第一個參數是陣列,回呼函數中的 Point 就代表我們的點類。

line.js —— 直線

 /** 直線 */
define(function() {
  return function(startPoint, endPoint) {
    this.startPoint = startPoint;
    this.endPoint   = endPoint;
    this.drawMe = function(context) {
      context.strokeStyle = "#000000";
      context.beginPath();
      context.moveTo(this.startPoint.x, this.startPoint.y);
      context.lineTo(this.endPoint.x, this.endPoint.y);
      context.closePath();
      context.stroke();
    };
  };
})

定義方式與點模組類似,但構造參數是兩個點物件(起點與終點),並多了一個 drawMe 方法,傳入 context 就能把自身畫出來。

rect.js —— 矩形

 /** 矩形 */
define(['app/point'], function() {
  return function(startPoint, width, height) {
    this.startPoint = startPoint;
    this.width  = width;
    this.height = height;
    this.drawMe = function(context) {
      context.strokeStyle = "#000000";
      context.strokeRect(this.startPoint.x, this.startPoint.y, this.width, this.height);
    };
  };
})

這裡的 define 帶上了依賴陣列 ['app/point']——因為矩形需要用到點。這正是 RequireJS 依賴注入的價值所在:模組自己聲明需求,載入器負責確保順序正確。

arc.js —— 圓形

 /** 圓形 */
define(function() {
  return function(startPoint, radius) {
    this.startPoint = startPoint;
    this.radius = radius;
    this.drawMe = function(context) {
      context.beginPath();
      context.arc(this.startPoint.x, this.startPoint.y,
                  this.radius, 0, 2 * Math.PI);
      context.closePath();
      context.stroke();
    };
  };
})

startPoint 代表圓心座標,radius 是半徑。以上三個模組都實作了 drawMe(),這是刻意的設計:讓不同圖形有一致的介面,呼叫端就不必判斷型別。若對 Canvas 繪圖不熟,可查閱 HTML 5 Canvas 參考手冊。

utils.js —— 繪圖管理工具

 /** 管理繪圖的工具 */
define(function() {
  var history = []; // 用來保存歷史繪製記錄,裡面存的是直線、矩形或圓形物件

  function drawLine(context, line) { line.drawMe(context); }
  function drawRect(context, rect) { rect.drawMe(context); }
  function drawArc(context, arc)   { arc.drawMe(context); }

  /** 添加一條繪製軌跡 */
  function addHistory(item) {
    history.push(item);
  }

  /** 畫出歷史軌跡 */
  function drawHistory(context) {
    for (var i = 0; i < history.length; i++) {
      history[i].drawMe(context);
    }
  }

  /** 清除歷史軌跡 */
  function clearHistory() {
    history = [];
  }

  return {
    drawLine: drawLine,
    drawRect: drawRect,
    drawArc: drawArc,
    addHistory: addHistory,
    drawHistory: drawHistory,
    clearHistory: clearHistory
  };
})

這個模組用一個 history 陣列保存所有已完成的圖形物件,並提供「重繪全部」與「清空」的能力。這是 Canvas 應用中很典型的做法——因為 Canvas 不像 SVG 那樣保留圖形物件,每次畫布更新都得把所有內容重畫一遍。把「物件」與「渲染」分離開來,正是靠這層記錄才能做到。

三、主介面與滑鼠事件

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>簡易繪圖程序</title>
<style type="text/css">
canvas {
  background-color: #ECECEC;
  cursor: default; /* 滑鼠設為預設的指標 */
}
.tool-bar { margin-bottom: 10px; }
</style>
</head>
<body>
<div class="tool-bar">
<button id="btn-line">畫直線</button>
<button id="btn-rect">畫矩形</button>
<button id="btn-oval">畫圓形</button>
<button id="btn-clear">清空畫布</button>
<span id="hint" style="color: red;">當前操作:畫直線</span>
</div>
<canvas id="canvas" width="800" height="600"</canvas>
<script type="text/javascript" src="js/require.min.js" data-main="js/main"</script>
<script type="text/javascript">
require(['app/point', 'app/line', 'app/rect', 'app/arc', 'app/utils'],
  function(Point, Line, Rect, Arc, Utils) {

  var canvas    = document.getElementById("canvas");
  var context   = canvas.getContext('2d');
  var canvasRect = canvas.getBoundingClientRect();

  canvas.addEventListener('mousedown', handleMouseDown);
  canvas.addEventListener('mousemove', handleMouseMove);
  canvas.addEventListener('mouseup',   handleMouseUp);

  bindClick('btn-clear', menuBtnClicked);
  bindClick('btn-line',  menuBtnClicked);
  bindClick('btn-rect',  menuBtnClicked);
  bindClick('btn-oval',  menuBtnClicked);

  var mouseDown = false;
  var selection = 1; // 0、1、2 分別代表畫直線、畫矩形、畫圓

  var downPoint = new Point(0, 0),
      movePoint = new Point(0, 0),
      upPoint   = new Point(0, 0);

  var line, rect, arc;

  /** 處理滑鼠按下的事件 */
  function handleMouseDown(event) {
    downPoint.x = event.clientX - canvasRect.left;
    downPoint.y = event.clientY - canvasRect.top;

    if (selection === 0) {
      line = new Line(downPoint, downPoint);
      line.startPoint = downPoint;
    } else if (selection === 1) {
      rect = new Rect(new Point(downPoint.x, downPoint.y), 0, 0);
    } else if (selection === 2) {
      arc = new Arc(new Point(downPoint.x, downPoint.y), 0);
    }
    mouseDown = true;
  }

  /** 處理滑鼠移動的事件 */
  function handleMouseMove(event) {
    movePoint.x = event.clientX - canvasRect.left;
    movePoint.y = event.clientY - canvasRect.top;

    if (movePoint.x == downPoint.x && movePoint.y == downPoint.y) { return; }
    if (movePoint.x == upPoint.x   && movePoint.y == upPoint.y)   { return; }

    if (mouseDown) {
      clearCanvas();

      if (selection == 0) {
        line.endPoint = movePoint;
        Utils.drawLine(context, line);
      } else if (selection == 1) {
        rect.width  = movePoint.x - downPoint.x;
        rect.height = movePoint.y - downPoint.y;
        Utils.drawRect(context, rect);
      } else if (selection == 2) {
        var x = movePoint.x - downPoint.x;
        var y = movePoint.y - downPoint.y;
        arc.radius = x > y ? (y / 2) : (x / 2);
        if (arc.radius < 0) { arc.radius = -arc.radius; }
        arc.startPoint.x = downPoint.x + arc.radius;
        arc.startPoint.y = downPoint.y + arc.radius;
        Utils.drawArc(context, arc);
      }

      Utils.drawHistory(context);
    }
  }

  /** 處理滑鼠抬起的事件 */
  function handleMouseUp(event) {
    upPoint.x = event.clientX - canvasRect.left;
    upPoint.y = event.clientY - canvasRect.top;

    if (mouseDown) {
      mouseDown = false;

      if (selection == 0) {
        line.endPoint = upPoint;
        if (!downPoint.equals(upPoint)) {
          Utils.addHistory(new Line(
            new Point(downPoint.x, downPoint.y),
            new Point(upPoint.x, upPoint.y)));
        }
      } else if (selection == 1) {
        rect.width  = upPoint.x - downPoint.x;
        rect.height = upPoint.y - downPoint.y;
        Utils.addHistory(new Rect(
          new Point(downPoint.x, downPoint.y), rect.width, rect.height));
      } else if (selection == 2) {
        Utils.addHistory(new Arc(
          new Point(arc.startPoint.x, arc.startPoint.y), arc.radius));
      }

      clearCanvas();
      Utils.drawHistory(context);
    }
  }

  /** 清空畫布 */
  function clearCanvas() {
    context.clearRect(0, 0, canvas.width, canvas.height);
  }

  /** 菜單按鈕的點擊事件處理 */
  function menuBtnClicked(event) {
    var domID = event.srcElement.id;
    if (domID === 'btn-clear') {
      clearCanvas();
      Utils.clearHistory();
    } else if (domID == 'btn-line') {
      selection = 0;
      showHint('當前操作:畫直線');
    } else if (domID == 'btn-rect') {
      selection = 1;
      showHint('當前操作:畫矩形');
    } else if (domID == 'btn-oval') {
      selection = 2;
      showHint('當前操作:畫圓形');
    }
  }

  function showHint(msg) {
    document.getElementById('hint').innerHTML = msg;
  }

  /** 給對應 id 的 dom 元素綁定點擊事件 */
  function bindClick(domID, handler) {
    document.getElementById(domID).addEventListener('click', handler);
  }
});
</script>
</body>
</html>

座標換算的關鍵

這段程式碼中最容易出錯的地方是取得滑鼠在 canvas 內的座標。event 物件提供的 clientX 與 clientY 是相對於整個頁面的座標,而繪圖需要的是相對於 canvas 左上角的座標。因此必須先用 getBoundingClientRect() 取得 canvas 在頁面上的位置,再用 clientX - canvasRect.left、clientY - canvasRect.top 換算。少了這一步,圖形就會畫到錯位的地方。

另一個值得注意的設計是「拖曳預覽」的做法:在 mousemove 中先 clearCanvas(),畫出當前正在拉的那個圖形,再把已完成的圖形全部重繪上去。因為 history 裡存的是物件而非像素,所以能隨時重算——這是模組化拆分帶來的直接好處。

原始碼與已知問題

本篇程式碼已托管到 GitHub,可點擊此處查看原始碼。

已知 bug

畫圓形時需要滑鼠從左上角拖向右下角,若不是這個方向,圓的位置會有偏移。原因在於圓心計算假設了 x、y 皆為正向位移。修正方式是把圓心改為兩點的中点,半徑取兩軸距離的較小值再除以二,並對負值取絕對值,就能支援任意拖曳方向。

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