Canvas 的 API 數量不多,但細節散落在各處。以下把日常最常用到的 24 個項目整理成一份速查表,寫 code 時隨時翻閱。
butt(對接,預設)、round(圓頭)、square(方頭)。miter(尖角,預設)、round(圓角)、bevel(斜角)。"bold 14px Arial"。start(預設)、end、left、right、center。top、hanging、middle、alphabetic(預設)、ideographic、bottom。變換是「乘法堆疊」的:連續呼叫會依序累加效果,所以做動畫時務必用 save() / restore() 包住,避免上一個物件的位移影響下一個。
context.fillStyle = "blue";
context.fillRect(10, 10, 100, 100);
context.globalCompositeOperation = 'lighter'; // 重疊處做加色
context.fillStyle = "red";
context.arc(110, 60, 50, 0, Math.PI * 2, false);
context.fill();
globalCompositeOperation 的常見取值:
source-over(預設):新圖形疊在舊圖形上。destination-over:新圖形畫在舊圖形之下。source-in:只保留新舊圖形重疊的部分。destination-in:只保留舊圖形與新圖形重疊的部分。source-out:只顯示新圖形沒有重疊到的部分。destination-out:舊圖形被新圖形遮掉的部分變透明。source-atop:新圖形只出現在與舊圖形重疊處,其餘舊圖形保留。destination-atop:舊圖形只在重疊處可見,其餘顯示新圖形。lighter:兩者都畫,重疊處做加色處理。xor:只畫不重疊的部分,重疊處透明。copy:只顯示新圖形。context.shadowOffsetX = 10; // 橫向位移
context.shadowOffsetY = 10; // 縱向位移
context.shadowColor = 'rgba(100,100,100,0.5)'; // 陰影顏色
context.shadowBlur = 7; // 模糊程度
context.drawImage(image, x, y);
context.drawImage(image, x, y, w, h);
context.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh);
context.createPattern(image, type); // type: no-repeat / repeat-x / repeat-y / repeat
context.clip(); // 依目前路徑裁剪
完整範例,示範局部放大與裁剪:
var image = new Image();
image.onload = function () { // 圖片載入後才畫,避免首次空白
drawImg(context, image);
};
image.src = "../images/wukong.gif";
function drawImg(context, image) {
context.drawImage(image, 10, 10, 125, 125); // 原圖
context.drawImage(image, 20, 0, 90, 100, 150, 10, 125, 125); // 局部放大
context.rect(20, 20, 80, 80);
context.clip(); // 只畫裁剪範圍內
context.drawImage(image, 0, 0, 200, 200);
}
若要做背景平鋪,可用 createPattern 產生 pattern 再當成 fillStyle:
var pattern = context.createPattern(image, 'repeat-y');
context.fillStyle = pattern;
context.fillRect(0, 0, 400, 400);
context.save() 把目前的繪圖狀態推入堆疊,context.restore() 從堆疊取出還原。要特別注意:保存的是「設定」而不是「已畫的內容」。會被保存的屬性包含 fillStyle、strokeStyle、lineWidth、lineCap、lineJoin、miterLimit、font、textAlign、textBaseline、globalAlpha、globalCompositeOperation、shadowColor、shadowBlur、shadowOffsetX/Y,以及目前的變換矩陣與裁剪範圍。
典型使用時機:物件需要位移旋轉、影像裁剪、或暫時切換樣式之後要還原。
// 線性漸層
var g = context.createLinearGradient(xStart, yStart, xEnd, yEnd);
g.addColorStop(0, 'red');
g.addColorStop(1, 'green');
context.fillStyle = g;
context.fillRect(0, 0, 200, 200);
// 放射狀漸層
var rg = context.createRadialGradient(x1, y1, r1, x2, y2, r2);
角度一律用弧度,換算方式是 弧度 = 度數 × Math.PI / 180。這條公式幾乎每個 Canvas 專案都會用到,記起來能省很多事。