原生 Canvas 繪圖時,每個方法或屬性前都要寫 ctx,程式碼容易顯得冗長。若借用 jQuery 的鏈式寫法,可以讓 Canvas 操作更簡潔。
ctx.moveTo(500, 0);
ctx.lineTo(500, 500);
ctx.strokeStyle = "#f00";
ctx.stroke();
ctx.moveTo(500, 0).lineTo(500, 500).strokeStyle("#f00").stroke();
可以建立一個代理物件,將 CanvasRenderingContext2D 的常用方法與屬性包裝起來,讓每個呼叫都回傳代理物件本身,就能串接後續操作。
// 讓 canvas 支援鏈式語法
~function () {
var pro = [
"save", "restore", "scale", "rotate", "translate", "transform",
"clearRect", "fillRect", "beginPath", "closePath", "moveTo", "lineTo",
"quadraticCurveTo", "bezierCurveTo", "arc", "rect", "fill", "stroke",
"clip", "fillText", "strokeText", "strokeRect", "drawImage",
"lineWidth", "strokeStyle", "globalAlpha", "fillStyle", "font",
"shadowOffsetX", "shadowOffsetY", "shadowBlur", "shadowColor",
"lineCap", "lineJoin", "miterLimit"
];
function XtendCanvas(canvas) {
var ctx = canvas.getContext("2d"),
fn = function () {},
fnP = fn.prototype;
for (var j = 0, p = pro[0]; p; p = pro[j++]) {
fn.prototype[p] = function (p) {
return function () {
var args = Array.prototype.slice.call(arguments);
if (typeof ctx[p] === "function") {
ctx[p].apply(ctx, args);
} else {
ctx[p] = args + "";
}
return fnP;
};
}(p);
}
return new fn();
}
window.XtendCanvas = XtendCanvas;
}();
var cvs = document.getElementById("cvs");
var ctx = XtendCanvas(cvs);
ctx.moveTo(500, 0).lineTo(500, 500).strokeStyle("#f00").stroke();
這種寫法並未改變 Canvas 的繪圖能力,只是透過原型與閉包,讓 API 呼叫更流暢。由於程式碼量不大,也方便嵌入現有的 JavaScript 工具庫中。