AngularJS 不只適合處理表單與清單,也能與 canvas 搭配,做出資料驅動的圖形效果。以下以圓形進度圖為例,說明如何透過模型變化觸發 canvas 重繪。
先在 controller 中定義進度資料,例如 label 與 percentage。
var APP = angular.module("APP", ["angular.directives-round-progress"]);
APP.controller("MainCtrl", function($scope) {
$scope.roundProgressData = {
label: 11,
percentage: 0.11
};
});畫面中的元素會被自訂 directive 取代成 canvas,並依模型內容繪製圓形進度。
directive 在 compile 階段先處理 DOM,例如建立 canvas、設定寬高與顏色。接著在 pre link 階段透過 $watch 監聽模型,當資料改變時重新繪製。
scope.$watch(expression, function(newValue) {
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, width, height);
var x = width / 2;
var y = height / 2;
ctx.beginPath();
ctx.arc(x, y, 100, 0, Math.PI * 2, false);
ctx.stroke();
var endAngle = (Math.PI * 2 * newValue.percentage) - (Math.PI / 2);
ctx.beginPath();
ctx.arc(x, y, 100, -(Math.PI / 2), endAngle, false);
ctx.stroke();
}, true);這個範例的關鍵在於:canvas 的繪製不是寫死的,而是由 $scope 中的資料決定。只要更新模型,畫面就會自動重繪,這正是 AngularJS 資料綁定思維的延伸。
若要做成通用元件,還可透過 data-* 屬性設定半徑、線寬、顏色與字型,讓同一個 directive 能套用到不同場景。