萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

Canvas 2D 繪圖 API 核心知識圖譜:24 大類方法屬性完整速查

Canvas 是 HTML5 核心繪圖能力,本文將 24 大類核心 API 按功能分類整理,附關鍵參數說明與典型用法,適合作為開發時的桌邊速查手冊。

1. 矩形操作

  • fillRect(x, y, w, h) — 填充矩形
  • strokeRect(x, y, w, h) — 描邊矩形
  • clearRect(x, y, w, h) — 清除矩形區域(變透明)

2. 樣式屬性

  • fillStyle — 填充樣式(顏色/漸變/圖案)
  • strokeStyle — 描邊樣式
  • lineWidth — 線條寬度
  • lineCap — 端點樣式:butt(默認)| round | square
  • lineJoin — 交點樣式:miter(默認尖角)| round | bevel

3. 路徑控制

  • beginPath() — 開始新路徑
  • closePath() — 閉合路徑(連回起點)
  • moveTo(x, y) — 移動筆觸(不畫線)
  • lineTo(x, y) — 畫直線到指定點

4. 曲線繪製

  • 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)

5. 文字繪製

  • fillText(text, x, y [, maxWidth]) — 填充文字
  • strokeText(text, x, y [, maxWidth]) — 描邊文字
  • font — 字體樣式(同 CSS font 簡寫)
  • textAlign — 水平對齊:start|end|left|right|center
  • textBaseline — 垂直對齊:top|hanging|middle|alphabetic|ideographic|bottom
  • measureText(text) — 返回 {width} 對象,測量文字寬度

6. 變換矩陣

  • rotate(angle) — 繞原點旋轉(弧度)
  • scale(x, y) — 縮放
  • translate(x, y) — 平移原點
  • transform(a, b, c, d, e, f) — 直接設定變換矩陣
  • setTransform(a, b, c, d, e, f) — 重置後再設定

7. 圖形合成

globalCompositeOperation 12 種模式:

值效果
source-over默認,新圖在上
destination-over新圖在下
source-in僅顯示重疊部分(新圖)
destination-in僅顯示重疊部分(舊圖)
source-out僅顯示非重疊(新圖)
destination-out僅顯示非重疊(舊圖)
source-atop新圖重疊部分 + 舊圖非重疊
destination-atop舊圖重疊部分 + 新圖非重疊
lighter重疊處顏色相加(發光效果)
xor重疊處透明
copy僅繪製新圖(忽略舊圖)

8. 陰影效果

  • shadowOffsetX、shadowOffsetY — 陰影偏移
  • shadowColor — 陰影顏色(建議用 rgba)
  • shadowBlur — 模糊半徑

9. 圖片繪製與處理

  • 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() — 將當前路徑設為裁切區域

10. 狀態棧

  • save() — 壓入當前繪圖狀態(不含像素內容)
  • restore() — 彈出恢復狀態
  • 適用場景:變換隔離、裁切隔離、樣式隔離

11. 漸變

  • 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 文檔 使用,快速定位參數細節。

copyright © 萬盛學電腦網 all rights reserved