Canvas 的 API 數量不少,但真正高頻使用的其實就是那幾十個。這裡把最常用到的 24 個知識點整理成一份速查表,分成矩形、路徑、文字、變換、圖像、漸層等區塊,寫作的時候可以直接對照。
fillRect(x, y, width, height)strokeRect(x, y, width, height)clearRect(x, y, width, height)fillStyle = "red",可為顏色、漸層或影像strokeStyle = "red"lineWidth = 4lineCap = "butt":butt(對接)/round(圓頭)/square(方頭),預設 buttlineJoin = "miter":miter(尖角)/round(圓角)/bevel(斜角),預設 miterbeginPath()closePath(),會自動補上一條回到起點的線段arc(x, y, radius, startAngle, endAngle, anticlockwise),角度以「弧度」為單位arcTo(x1, y1, x2, y2, radius):從上一點畫弧到 (x2, y2),並以指定半徑通過 (x1, y1)moveTo(x, y):只移動位置,不產生線條lineTo(x, y):從上一點連一條直線過來quadraticCurveTo(cx, cy, x, y),一个控制點bezierCurveTo(cx1, cy1, cx2, cy2, x, y),兩個控制點rect(x, y, width, height):產生的是矩形「路徑」,可後續填滿或描邊,與 fillRect 直接成像不同fillText("hello", x, y, maxWidth)strokeText("hello", x, y, maxWidth)font = "bold 14px Arial"textAlign = 'start'(start/end/left/right/center,預設 start)textBaseline = 'alphabetic'(top/hanging/middle/alphabetic/ideographic/bottom,預設 alphabetic)context.measureText(text).widthrotate(angle):繞原點旋轉,參數為弧度。等效寫法:transform(Math.cos(a), Math.sin(a), -Math.sin(a), Math.cos(a), 0, 0),其中 a 為弧度。scale(x, y):縮放,等效 transform(x, 0, 0, y, 0, 0)translate(x, y):把座標原點移到 (x, y),等效 transform(1, 0, 0, 1, x, y)transform(a, b, c, d, e, f):以矩陣「相乘」的方式疊加變換setTransform(a, b, c, d, e, f):先把矩陣重置為單位矩陣,再套用變換角度與弧度換算永遠是:弧度 = 角度 × Math.PI / 180。
透過 globalCompositeOperation 可以控制新圖形與既有圖形如何合成:
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();
可選值:
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); // 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 物件
image.src = "../images/wukong.gif";
var test = context.createPattern(image, 'repeat-y');
context.fillStyle = test;
context.fillRect(0, 0, 400, 400);
// 用 onload 確保圖片載入完成後才繪製。
// 對於較大的網路圖檔,這樣可以邊載入邊畫,避免第一次渲染時什麼都看不到。
image.onload = function () {
drawImg(context, image);
};
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); // 只在裁剪範圍內作畫
}
context.save() 會把目前的狀態堆進堆疊,context.restore() 則把上一個狀態取出來。要注意的是:保存的只是「繪圖設定與變換矩陣」,並不包含已經畫上去的像素內容。
常被保存的屬性包含:fillStyle、font、globalAlpha、globalCompositeOperation、lineCap、lineJoin、lineWidth、miterLimit、shadowBlur、shadowColor、shadowOffsetX、shadowOffsetY、strokeStyle、textAlign、textBaseline。
典型使用時機:
var g = context.createLinearGradient(xStart, yStart, xEnd, yEnd); // 線性漸層 var g1 = context.createRadialGradient(xStart, yStart, rStart, xEnd, yEnd, rEnd); // 放射狀漸層 g.addColorStop(0, 'red'); g.addColorStop(1, 'green'); context.fillStyle = g; context.fillRect(0, 0, 200, 200);
addColorStop(offset, color) 的 offset 是 0 到 1 之間的數字,代表顏色在漸層中的位置。
把這 24 個要點記熟,基本上一般的 Canvas 繪圖需求都能應付;剩下的進階話題(像素操作、WebGL、離屏畫布)都是在此之上的延伸。