HTML5 可視化三大支柱
現代 Web 可視化不再依賴 Flash/Java Applet/Silverlight,而是建立在三大原生技術支柱之上:**Canvas 2D/3D (WebGL)**、**CSS3 進階視覺效果**、**SVG (可縮放向量圖形)**。本文聚焦 Canvas 2D 與 CSS3 視覺特性,並針對行動裝置優化策略深入探討。
一、Canvas 2D 繪圖 API 核心實戰
基本繪圖流程
const canvas = document.getElementById('chart');
const ctx = canvas.getContext('2d');
// 設定實際繪圖解析度 (應對高 DPR 螢幕)
const dpr = window.devicePixelRatio || 1;
canvas.width = canvas.clientWidth * dpr;
canvas.height = canvas.clientHeight * dpr;
ctx.scale(dpr, dpr); // 縮放繪圖上下文,CSS 像素單位不變
// 繪製長條圖範例
function drawBarChart(data, options = {}) {
const {width, height, padding = 40, maxValue = Math.max(...data)} = options;
const barWidth = (width - padding * 2) / data.length * 0.8;
const gap = (width - padding * 2) / data.length * 0.2;
// 清除畫布
ctx.clearRect(0, 0, width, height);
// 座標軸
ctx.strokeStyle = '#333';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(padding, padding);
ctx.lineTo(padding, height - padding);
ctx.lineTo(width - padding, height - padding);
ctx.stroke();
// 網格線與 Y 軸標籤
ctx.strokeStyle = 'rgba(0,0,0,0.1)';
ctx.font = '12px system-ui';
ctx.fillStyle = '#666';
ctx.textAlign = 'right';
ctx.textBaseline = 'middle';
const gridLines = 5;
for (let i = 0; i <= gridLines; i++) {
const y = padding + (height - 2*padding) * i / gridLines;
const val = Math.round(maxValue * (1 - i/gridLines));
ctx.beginPath();
ctx.moveTo(padding, y);
ctx.lineTo(width - padding, y);
ctx.stroke();
ctx.fillText(val, padding - 8, y);
}
// 長條
data.forEach((value, i) => {
const x = padding + gap/2 + i * (barWidth + gap);
const barHeight = (value / maxValue) * (height - 2*padding);
const y = height - padding - barHeight;
// 漸層填充
const grad = ctx.createLinearGradient(x, y, x, y + barHeight);
grad.addColorStop(0, '#4facfe');
grad.addColorStop(1, '#00f2fe');
ctx.fillStyle = grad;
ctx.fillRect(x, y, barWidth, barHeight);
// 數值標籤
ctx.fillStyle = '#333';
ctx.textAlign = 'center';
ctx.fillText(value, x + barWidth/2, y - 5);
// X 軸標籤
ctx.fillStyle = '#666';
ctx.textAlign = 'center';
ctx.fillText(`項目${i+1}`, x + barWidth/2, height - padding + 20);
});
}
// 使用
drawBarChart([120, 200, 150, 300, 180, 250, 90], {width: 600, height: 400});
Canvas 核心 API 速查
| 類別 | API | 用途 |
| 路徑 | `beginPath()`, `moveTo()`, `lineTo()`, `closePath()` | 建立路徑 |
| `arc()`, `arcTo()`, `ellipse()` | 圓弧/橢圓 |
| `bezierCurveTo()`, `quadraticCurveTo()` | 貝茲曲線 |
| `rect()`, `roundRect()` (新) | 矩形/圓角矩形 |
| 繪製 | `fill()`, `stroke()` | 填充/描邊路徑 |
| `fillRect()`, `strokeRect()`, `clearRect()` | 直接繪製矩形 |
| `fillText()`, `strokeText()`, `measureText()` | 文字繪製與測量 |
| 樣式 | `fillStyle`, `strokeStyle` (顏色/漸層/圖案) | 填充/描邊樣式 |
| `lineWidth`, `lineCap`, `lineJoin`, `lineDashOffset`, `setLineDash()` | 線條樣式 |
| `shadowColor`, `shadowBlur`, `shadowOffsetX/Y` | 陰影 |
| 變換 | `translate()`, `rotate()`, `scale()`, `transform()`, `setTransform()` | 座標系變換 |
| `save()`, `restore()` | 保存/恢復繪圖狀態棧 |
| `getTransform()` (新) | 取得當前變換矩陣 |
| 圖像 | `drawImage(img, sx, sy, sw, sh, dx, dy, dw, dh)` | 繪製圖片/Canvas/Video |
| `createImageData()`, `getImageData()`, `putImageData()` | 像素級操作 |
| 合成 | `globalCompositeOperation` | 混合模式 (source-over, multiply, destination-out 等) |
| `globalAlpha` | 全域透明度 |
| 擊中測試 | `isPointInPath()`, `isPointInStroke()` | 滑鼠互動判定 |
高效能技巧
- OffscreenCanvas:Web Worker 內離屏渲染,不阻塞主執行緒 (`canvas.transferControlToOffscreen()`)。
- 批次繪製:合併相同 `fillStyle`/`strokeStyle` 的繪製呼叫,減少狀態切換。
- 請求動畫幀節流:`requestAnimationFrame` 配合 `performance.now()` 計算 delta time,避免過度繪製。
- 圖層分離:靜態背景 (座標軸、網格) 繪製在底層 Canvas,動態數據 (長條、線條) 繪製在上層 Canvas,僅重繪上層。
- 像素操作優化:`getImageData`/`putImageData` 極慢,能用濾鏡 (`filter: blur()`) 或合成模式替代就替代。
二、CSS3 奇妙視覺世界:漸層、陰影、變換、濾鏡、動畫
關鍵視覺屬性速查
| 屬性 | 核心語法 | 視覺效果 |
background | `linear-gradient(45deg, #ff6b6b, #feca57)`, `radial-gradient(circle at 50% 50%, #fff, #000)`, `conic-gradient(from 0deg, #f00, #0f0, #00f)` | 線性/徑向/圓錐漸層,支援多色標、透明度、重複 |
box-shadow | `0 10px 30px rgba(0,0,0,0.1), 0 0 0 1px rgba(0,0,0,0.05) inset` | 多層陰影、內陰影、霓虹發光、拟态 (Neumorphism) |
transform | `translate3d(x,y,z) rotate(45deg) scale(1.2) skew(10deg)` | 2D/3D 變換,GPU 加速關鍵 |
filter | `blur(8px) brightness(1.2) contrast(1.1) saturate(1.5) hue-rotate(90deg) drop-shadow(0 4px 6px rgba(0,0,0,0.1))` | 圖像濾鏡,比 Canvas 像素操作快得多 |
backdrop-filter | `blur(20px) saturate(1.5)` | 背景模糊/玻璃態 (Glassmorphism) |
clip-path | `polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%)`, `circle(50% at 50% 50%)` | 任意形狀裁切 |
mask-image | `url(mask.svg)`, `linear-gradient(transparent, black)` | 遮罩/透明度控制 |
@keyframes + `animation` | `animation: slideIn 0.5s cubic-bezier(0.25,0.46,0.45,0.94) forwards` | 關鍵幀動畫、緩動函數、填充模式 |
transition | `transition: all 0.3s ease-out` | 狀態變化過渡 |
@property (Houdini) | `@property --my-color { syntax: ''; inherits: false; initial-value: red; }` | 註冊自定義屬性型別,啟用插值動畫 |
實戰:純 CSS 繪製 iOS 風格開關
<label class="ios-switch">
<input type="checkbox">
<span class="slider"></span>
</label>
<style>
.ios-switch { position: relative; display: inline-block; width: 52px; height: 32px; }
.ios-switch input { opacity: 0; width: 0; height: 0; }
.slider {
position: absolute; inset: 0; border-radius: 16px;
background: #ccc; transition: background 0.3s;
cursor: pointer;
}
.slider::before {
content: ''; position: absolute; width: 24px; height: 24px; border-radius: 50%;
top: 4px; left: 4px; background: white; box-shadow: 0 2px 6px rgba(0,0,0,0.2);
transition: transform 0.3s cubic-bezier(0.25,0.46,0.45,0.94);
}
input:checked + .slider { background: #34c759; }
input:checked + .slider::before { transform: translateX(20px); }
input:focus-visible + .slider { box-shadow: 0 0 0 3px rgba(52,199,89,0.4); }
</style>
三、行動裝置優化實戰指南
1. 高 DPR (Device Pixel Ratio) 適配
- Canvas:`canvas.width = cssWidth * dpr; ctx.scale(dpr, dpr)`。
- CSS:`background-image: url(img@2x.webp);` + `image-set()` 或 `` + `srcset` 響應式圖片。
- Meta 標籤:``。
2. 觸控事件與滑動流暢度
- 使用 `touch-action: pan-y` / `pan-x` / `manipulation` 控制瀏覽器預設滑動行為。
- 被動事件監聽器:`el.addEventListener('touchmove', handler, {passive: true})` 避免阻塞滾動。
- 避免在觸控處理器中執行重計算/佈局,使用 `requestAnimationFrame` 延遲至下一幀。
3. 效能預算與指標
| 指標 | 目標 | 測量工具 |
| FCP (First Contentful Paint) | < 1.8s | Lighthouse, Web Vitals |
| LCP (Largest Contentful Paint) | < 2.5s | Lighthouse, Chrome UX Report |
| CLS (Cumulative Layout Shift) | < 0.1 | Lighthouse, Layout Shift API |
| FID / INP (Interaction to Next Paint) | < 100ms / < 200ms | Web Vitals, Chrome DevTools |
| 幀率 | 持續 60fps (16.67ms/幀) | DevTools Performance, requestAnimationFrame 計時 |
| 記憶體 | < 50MB (低端裝置) | DevTools Memory, `performance.measureUserTiming()` |
4. 電池與熱節流意識
- 避免無限循環的高頻 Canvas 重繪 (如粒子系統),改用 `requestAnimationFrame` + 可見性判斷 (`document.visibilityState`)。
- 使用 `navigator.getBattery()` (已棄用但仍可用) 或觀察 `navigator.connection` (Network Information API) 調整動畫複雜度/頻率。
- CSS `content-visibility: auto` 跳過離螢幕元素渲染。
四、Canvas vs SVG vs CSS vs WebGL 選型決策樹
需要無限縮放、DOM 事件綁定、無障礙語意化、圖層較少 (<1000)?
├─ 是 → SVG (圖表、圖示、地圖、可編輯圖形)
└─ 否 → 需高效能像素級控制、粒子特效、遊戲、大數據點 (>10k)?
├─ 是 → WebGL (Three.js, PixiJS, Deck.gl) 或 Canvas 2D (簡單 2D)
└─ 否 → 需聲明式、響應式、樣式化、無障礙、SEO 友好?
├─ 是 → 純 CSS/HTML (佈局、UI 元件、簡單動畫、圖表輔助)
└─ 否 → Canvas 2D (圖表、繪圖板、影像編輯、簡單遊戲)
總結
HTML5 可視化 UI 的核心在於**選對技術棧**、**善用 GPU 加速** (`transform3d`, `will-change`, `OffscreenCanvas`)、**尊重裝置限制** (DPR、電池、熱節流、觸控延遲)、**遵循無障礙標準** (語意化、鍵盤操作、減弱動畫、高對比度)。Canvas 2D 適合程式化繪圖與像素操作,CSS3 適合聲明式 UI 與轉場動畫,兩者結合並輔以 SVG/WebGL,構建現代、高效能、跨裝置的 Web 視覺體驗。