Canvas API 繁多,但核心高頻知識點其實有限。本文提煉 24 條必須掌握的基礎知識,涵蓋矩形、路徑、文本、變換、合成、陰影、圖片、漸變、狀態管理,適合作為速查表與面試複習資料。
矩形三大金剛
- fillRect(x, y, w, h):填充矩形
- strokeRect(x, y, w, h):描邊矩形框
- clearRect(x, y, w, h):清空矩形區域(透明)
樣式雙雄
- fillStyle:填充樣式(顏色/漸變/模式)
- strokeStyle:描邊樣式
線條三屬性
- lineWidth:線寬
- lineCap:端點 butt/round/square
- lineJoin:轉角 miter/round/bevel
路徑五步曲
- beginPath():開啟新路徑
- closePath():閉合路徑(連回起點)
- moveTo(x, y):移動筆尖
- lineTo(x, y):畫直線
- arc(x, y, r, sA, eA, ccw):圓弧/圓
曲線雙雄
- quadraticCurveTo(cpx, cpy, x, y):二次貝塞爾(一個控制點)
- bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y):三次貝塞爾(兩個控制點)
矩形路徑
- rect(x, y, w, h):添加矩形路徑(非直接繪製,需配合 stroke/fill)
文本六要素
- fillText(text, x, y, maxW?):填充文本
- strokeText(text, x, y, maxW?):描邊文本
- font:字體 CSS 字符串
- textAlign:start/end/left/right/center
- textBaseline:top/hanging/middle/alphabetic/ideographic/bottom
- measureText(text):獲取文本度量信息
變換五式
- translate(x, y):平移原點
- rotate(angle):旋轉(弧度)
- scale(x, y):縮放
- transform(a,b,c,d,e,f):直接設置矩陣
- setTransform(a,b,c,d,e,f):重置後應用矩陣
合成操作
- globalCompositeOperation:源/目標混合模式
常用值:
'source-over' // 默認,新圖在上
'destination-over' // 新圖在下
'source-in' // 僅顯示重疊部分(新圖)
'destination-in' // 僅顯示重疊部分(舊圖)
'source-out' // 僅顯示非重疊部分(新圖)
'destination-out' // 僅顯示非重疊部分(舊圖)
'source-atop' // 新圖重疊部分 + 舊圖非重疊
'destination-atop' // 舊圖重疊部分 + 新圖非重疊
'lighter' // 重疊處加色(發光效果)
'xor' // 僅非重疊,重疊透明
'copy' // 僅新圖(清除舊圖)
陰影四屬性
- shadowOffsetX、shadowOffsetY:偏移
- shadowColor:顏色
- shadowBlur:模糊半徑
圖片操作三板斧
- drawImage(img, dx, dy [, dw, dh] [, sx, sy, sw, sh, dx, dy, dw, dh]):繪製/裁剪/縮放
- createPattern(image, repetition):創建平鋪模式
- clip():裁剪區域(基於當前路徑)
狀態棧
- save():壓棧(保存樣式、變換、裁剪、虛線等)
- restore():出棧恢復
應用場景:變形、裁剪、臨時修改樣式後恢復。
漸變雙子星
- createLinearGradient(x0,y0,x1,y1):線性漸變
- createRadialGradient(x0,y0,r0,x1,y1,r1):徑向漸變
配合 addColorStop(offset, color) 定義色標。
補充:高頻實用技巧
- 虛線:
ctx.setLineDash([10,5]) + ctx.lineDashOffset 動畫
- 圓角矩形:
roundRect 或新 API ctx.roundRect(x,y,w,h,r)(現代瀏覽器)
- 橢圓:
ctx.ellipse(x,y,rx,ry,rot,sA,eA,ccw)
- 路徑檢測:
ctx.isPointInPath(x,y) / isPointInStroke(x,y)
- 圖片平滑:
ctx.imageSmoothingEnabled = false(像素風)
- 像素操作:
getImageData/putImageData 實現濾鏡
- 導出圖片:
canvas.toDataURL('image/png') / toBlob(callback, type, quality)
這 24+ 條知識點構成了 Canvas 2D 開發的骨架。建議將此表格保存為 Markdown/Notion 頁面,遇到遺忘快速檢索;實戰中遇到新 API(如 Path2D、OffscreenCanvas、canvas.getContext('2d', {willReadFrequently: true}))再按需補充。