Canvas 2D 渲染上下文提供了豐富的繪圖 API。本文按功能模塊整理核心方法與屬性,附帶常用代碼片段,適合作為開發時的桌邊參考手冊。
畫布狀態管理
| 方法 | 說明 |
save() | 將當前繪圖狀態(樣式、變換、裁剪區等)壓入棧 |
restore() | 彈出棧頂狀態並恢復 |
getContext('2d') | 獲取 2D 渲染上下文 |
toDataURL(type, quality) | 導出畫布圖片數據 URL(支持 image/png、image/jpeg、image/webp) |
線條樣式
| 屬性 | 說明 | 默認值 |
lineWidth | 線條寬度 | 1 |
lineCap | 端點樣式:butt/round/square | butt |
lineJoin | 交點樣式:miter/round/bevel | miter |
miterLimit | 最大斜接長度 | 10 |
setLineDash(segments) | 虛線模式,如 [5, 3] | [] |
lineDashOffset | 虛線偏移量 | 0 |
顏色、漸變與陰影
| 屬性/方法 | 說明 |
fillStyle | 填充樣式:顏色、漸變、模式 |
strokeStyle | 描邊樣式 |
shadowColor | 陰影顏色 |
shadowBlur | 陰影模糊半徑 |
shadowOffsetX/Y | 陰影偏移 |
createLinearGradient(x0,y0,x1,y1) | 創建線性漸變對象 |
createRadialGradient(x0,y0,r0,x1,y1,r1) | 創建徑向漸變對象 |
createPattern(image, repetition) | 創建圖案(repeat/repeat-x/repeat-y/no-repeat) |
gradient.addColorStop(offset, color) | 添加漸變色標(0-1) |
路徑繪製
| 方法 | 說明 |
beginPath() | 開始新路徑/重置 |
moveTo(x, y) | 移動筆尖不畫線 |
lineTo(x, y) | 畫直線到指定點 |
closePath() | 閉合路徑(連回起點) |
rect(x, y, w, h) | 矩形路徑 |
arc(x, y, r, sAngle, eAngle, ccw) | 圓弧路徑 |
arcTo(x1,y1,x2,y2,r) | 切線圓弧(常用於圓角矩形) |
quadraticCurveTo(cpx,cpy,x,y) | 二次貝塞爾曲線 |
bezierCurveTo(cp1x,cp1y,cp2x,cp2y,x,y) | 三次貝塞爾曲線 |
ellipse(x,y,rx,ry,rot,sA,eA,ccw) | 橢圓弧(較新 API) |
fill() | 填充路徑 |
stroke() | 描邊路徑 |
clip() | 將路徑設為裁剪區 |
isPointInPath(x, y) | 點是否在路徑內 |
矩形快捷方法
fillRect(x,y,w,h):填充矩形
strokeRect(x,y,w,h):描邊矩形
clearRect(x,y,w,h):清空矩形區域(透明)
文本繪製
| 屬性/方法 | 說明 |
font | 字體:'bold 16px Microsoft YaHei' |
textAlign | 水平對齊:start/end/left/right/center |
textBaseline | 垂直基線:top/hanging/middle/alphabetic/ideographic/bottom |
fillText(text, x, y, maxWidth) | 填充文本 |
strokeText(text, x, y, maxWidth) | 描邊文本 |
measureText(text) | 返回 {width} 對象,獲取文本寬度 |
變換矩陣
| 方法 | 說明 |
translate(x, y) | 平移原點 |
rotate(angle) | 旋轉(弧度) |
scale(x, y) | 縮放 |
transform(a,b,c,d,e,f) | 直接設置變換矩陣 |
setTransform(a,b,c,d,e,f) | 重置為單位矩陣再應用 transform |
resetTransform() | 重置為單位矩陣(現代 API) |
圖片繪製
drawImage(image, dx, dy)
drawImage(image, dx, dy, dWidth, dHeight)
drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)
image:HTMLImageElement/HTMLCanvasElement/HTMLVideoElement/ImageBitmap
- 注意:圖片必須載入完成(
onload)後繪製,否則為空
像素操作
createImageData(w, h)/getImageData(sx, sy, sw, sh)
putImageData(imagedata, dx, dy)
- 應用:濾鏡、圖像處理、截圖、像素級碰撞檢測
實用代碼片段
圓角矩形
function roundRect(ctx, x, y, w, h, r) {
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + w, y, x + w, y + h, r);
ctx.arcTo(x + w, y + h, x, y + h, r);
ctx.arcTo(x, y + h, x, y, r);
ctx.arcTo(x, y, x + w, y, r);
ctx.closePath();
}
多邊形
function polygon(ctx, x, y, radius, sides, startAngle = -Math.PI/2) {
ctx.beginPath();
ctx.moveTo(x + radius * Math.cos(startAngle), y + radius * Math.sin(startAngle));
for (let i = 1; i <= sides; i++) {
const angle = startAngle + i * 2 * Math.PI / sides;
ctx.lineTo(x + radius * Math.cos(angle), y + radius * Math.sin(angle));
}
ctx.closePath();
}
此速查表涵蓋 90% 日常開發場景。建議收藏並結合 MDN 文檔深入學習各 API 邊界行為與瀏覽器兼容性。