Canvas 是 HTML5 核心繪圖能力,本文將 24 大類核心 API 按功能分類整理,附關鍵參數說明與典型用法,適合作為開發時的桌邊速查手冊。
fillRect(x, y, w, h) — 填充矩形strokeRect(x, y, w, h) — 描邊矩形clearRect(x, y, w, h) — 清除矩形區域(變透明)fillStyle — 填充樣式(顏色/漸變/圖案)strokeStyle — 描邊樣式lineWidth — 線條寬度lineCap — 端點樣式:butt(默認)| round | squarelineJoin — 交點樣式:miter(默認尖角)| round | bevelbeginPath() — 開始新路徑closePath() — 閉合路徑(連回起點)moveTo(x, y) — 移動筆觸(不畫線)lineTo(x, y) — 畫直線到指定點arc(x, y, r, start, end, anticlockwise) — 圓弧/圓arcTo(x1, y1, x2, y2, r) — 切線圓弧quadraticCurveTo(cx, cy, x, y) — 二次貝塞爾曲線bezierCurveTo(cx1, cy1, cx2, cy2, x, y) — 三次貝塞爾曲線rect(x, y, w, h) — 矩形路徑(不直接繪製,需配合 fill/stroke)fillText(text, x, y [, maxWidth]) — 填充文字strokeText(text, x, y [, maxWidth]) — 描邊文字font — 字體樣式(同 CSS font 簡寫)textAlign — 水平對齊:start|end|left|right|centertextBaseline — 垂直對齊:top|hanging|middle|alphabetic|ideographic|bottommeasureText(text) — 返回 {width} 對象,測量文字寬度rotate(angle) — 繞原點旋轉(弧度)scale(x, y) — 縮放translate(x, y) — 平移原點transform(a, b, c, d, e, f) — 直接設定變換矩陣setTransform(a, b, c, d, e, f) — 重置後再設定globalCompositeOperation 12 種模式:
| 值 | 效果 |
|---|---|
source-over | 默認,新圖在上 |
destination-over | 新圖在下 |
source-in | 僅顯示重疊部分(新圖) |
destination-in | 僅顯示重疊部分(舊圖) |
source-out | 僅顯示非重疊(新圖) |
destination-out | 僅顯示非重疊(舊圖) |
source-atop | 新圖重疊部分 + 舊圖非重疊 |
destination-atop | 舊圖重疊部分 + 新圖非重疊 |
lighter | 重疊處顏色相加(發光效果) |
xor | 重疊處透明 |
copy | 僅繪製新圖(忽略舊圖) |
shadowOffsetX、shadowOffsetY — 陰影偏移shadowColor — 陰影顏色(建議用 rgba)shadowBlur — 模糊半徑drawImage(img, x, y) / drawImage(img, x, y, w, h) / drawImage(img, sx, sy, sw, sh, dx, dy, dw, dh) — 三種重載createPattern(img, 'repeat'|'repeat-x'|'repeat-y'|'no-repeat') — 建立圖案填充clip() — 將當前路徑設為裁切區域save() — 壓入當前繪圖狀態(不含像素內容)restore() — 彈出恢復狀態createLinearGradient(x0, y0, x1, y1) — 線性漸變createRadialGradient(x0, y0, r0, x1, y1, r1) — 放射漸變addColorStop(offset, color) — 添加色標(0~1)| 類別 | 核心 API |
|---|---|
| 矩形 | fillRect, strokeRect, clearRect |
| 樣式 | fillStyle, strokeStyle, lineWidth, lineCap, lineJoin |
| 路徑 | beginPath, closePath, moveTo, lineTo |
| 曲線 | arc, arcTo, quadraticCurveTo, bezierCurveTo, rect |
| 文字 | fillText, strokeText, font, textAlign, textBaseline, measureText |
| 變換 | rotate, scale, translate, transform, setTransform |
| 合成 | globalCompositeOperation (12 模式) |
| 陰影 | shadowOffsetX/Y, shadowColor, shadowBlur |
| 圖片 | drawImage (3重載), createPattern, clip |
| 狀態 | save, restore |
| 漸變 | createLinearGradient, createRadialGradient, addColorStop |
建議收藏本表,開發時配合 MDN Canvas API 文檔 使用,快速定位參數細節。