把平時最常用的 Canvas 繪圖知識整理成一份清單,寫的時候能隨手翻,不用再去翻文檔。以下 24 條基本涵蓋了 2D 繪圖的大部分日常場景。
1. fillRect(x, y, width, height)——填充矩形,用當前 fillStyle 上色。
2. strokeRect(x, y, width, height)——只畫矩形邊框,線條樣式由 strokeStyle 與 lineWidth 決定。
3. clearRect(x, y, width, height)——把指定區域擦成透明,常用於動畫每幀的清屏。
4. fillStyle:填充樣式,可為純色、漸變物件或 pattern,例如 fillStyle = "red"。
5. strokeStyle:描邊樣式,取值規則同上。
6. lineWidth = 4:線寬,單位是像素。
7. lineCap = "butt":線段端點樣式,可選 butt(齊平,預設)、round(圓頭)、square(方形,比 butt 多出半個線寬)。
8. lineJoin = "miter":線段交角樣式,可選 miter(尖角,預設)、round(圓角)、bevel(斜切)。
9. beginPath():開啟一條新路徑。連續繪製多個圖形時,忘了呼叫它會導致路徑互相殘留。
10. closePath():闭合路徑,等於自動補上一條回到起點的線。
11. arc(x, y, radius, startAngle, endAngle, anticlockwise):畫圓或圓弧,角度以弧度為單位,最後一個參數為 true 表示逆時針。
12. arcTo(x1, y1, x2, y2, radius):從當前點畫一段切於兩條假想線的弧線,終點落在 x2、y2 方向上,並以 radius 為半徑貼近轉角點 (x1, y1)。常用來畫圓角。
13. moveTo(x, y):把「筆尖」搬到 (x, y),但不留下任何線條。
14. lineTo(x, y):從當前點畫一条直线到 (x, y)。
15. quadraticCurveTo(cx, cy, x, y):二次貝茲曲線,(cx, cy) 是唯一控制點。
16. bezierCurveTo(cx1, cy1, cx2, cy2, x, y):三次貝茲曲線,兩個控制點帶來更自由的弧度變化。
17. rect(x, y, width, height):直接把矩形加入當前路徑,注意它產生的是「路徑」而非獨立圖形,後面還需要 fill 或 stroke 才看得到。
18. 文本相關API
(1) fillText("hello", x, y, maxWidth):填充文字,maxWidth 為可選的最大寬度,超寬時文字會被壓縮。
(2) strokeText("hello", x, y, maxWidth):文字描邊。
(3) font = "bold 14px Arial":寫法與 CSS 的 font 簡寫一致。
(4) textAlign = 'start':水平對齊,可選 start、end、left、right、center,預設 start,以 (x, y) 所在的垂直軸為基準。
(5) textBaseline = 'alphabetic':垂直對齊,可選 top、hanging、middle、alphabetic、ideographic、bottom,預設 alphabetic,以 (x, y) 所在的水平軸為基準。
(6) context.measureText(text).width:取得文字的實際像素寬度,做置中或換行判斷時很好用。
19. 變換相關API
(1) rotate(angle):以原點為中心旋轉 angle 弧度,等價於 transform(cos, sin, -sin, cos, 0, 0)。
(2) scale(x, y):縮放,等價於 transform(x, 0, 0, y, 0, 0)。
(3) translate(x, y):平移坐標原點,之後的 (0, 0) 就落在原本的 (x, y) 上。
(4) transform(a, b, c, d, e, f):在目前變換矩陣上「再乘」一個矩陣,效果會累加。
(5) setTransform(a, b, c, d, e, f):先把矩陣重置為單位矩陣,再套用新矩陣,是徹底歸零的做法。
透過 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(只留新圖)。
21. 陰影四參數
context.shadowOffsetX = 10; // 水平位移 context.shadowOffsetY = 10; // 垂直位移 context.shadowColor = 'rgba(100,100,100,0.5)'; // 陰影顏色 context.shadowBlur = 7; // 模糊半徑
22. 圖像相關API
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(); // 依當前路徑設定裁剪範圍
一個把平鋪、局部放大與裁剪串起來的例子:
image = new Image();
image.src = "../images/wukong.gif";
var test = context.createPattern(image, 'repeat-y');
context.fillStyle = test;
context.fillRect(0, 0, 400, 400);
image.onload = function() {
// 放在 onload 裡,圖片可以邊載入邊繪製,不必等整張圖下載完
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);
}
23. save() / restore()
context.save() 把目前的狀態壓入堆疊,context.restore() 取出最近一次保存的狀態。要留意:保存的是「繪圖設定與變換矩陣」,不是已經畫上去的像素。
典型用途:
(1) 圖形或圖像變形後需要復原;
(2) 裁剪區域用完要還原;
(3) 臨時改動 fillStyle、font、globalAlpha、globalCompositeOperation、lineCap、lineJoin、lineWidth、miterLimit、shadowBlur、shadowColor、shadowOffsetX/Y、strokeStyle、textAlign、textBaseline 等上下文屬性時。
24. 線性與放射漸變
var g = context.createLinearGradient(xStart, yStart, xEnd, yEnd); var g1 = context.createRadialGradient(xStart, yStart, radiusStart, xEnd, yEnd, radiusEnd); g.addColorStop(0, 'red'); g.addColorStop(1, 'green'); context.fillStyle = g; context.fillRect(0, 0, 200, 200);
addColorStop 的第一個參數是 0 到 1 之間的停靠位置,實際專案裡通常會放 2 到 3 個色點,過渡會更自然。