function rotateImage(img, angleDeg) {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const rad = angleDeg * Math.PI / 180;
// 計算旋轉後邊界框
const w = img.width, h = img.height;
const sin = Math.abs(Math.sin(rad)), cos = Math.abs(Math.cos(rad));
const newW = Math.round(w * cos + h * sin);
const newH = Math.round(w * sin + h * cos);
canvas.width = newW;
canvas.height = newH;
// 移動原點到中心 → 旋轉 → 繪製
ctx.translate(newW / 2, newH / 2);
ctx.rotate(rad);
ctx.drawImage(img, -w / 2, -h / 2);
return canvas; // 可轉 Blob/DataURL/放入新 Image
}
function rotate90(img, times) { // times: 1=90°, 2=180°, 3=270°
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
times = ((times % 4) + 4) % 4;
if (times === 0) return img; // 直接返回原圖
const [w, h] = times % 2 === 1 ? [img.height, img.width] : [img.width, img.height];
canvas.width = w; canvas.height = h;
switch (times) {
case 1: // 90° CW
ctx.translate(w, 0);
ctx.rotate(Math.PI / 2);
break;
case 2: // 180°
ctx.translate(w, h);
ctx.rotate(Math.PI);
break;
case 3: // 270° CW (90° CCW)
ctx.translate(0, h);
ctx.rotate(-Math.PI / 2);
break;
}
ctx.drawImage(img, 0, 0);
return canvas;
}
async function loadAndCorrectOrientation(file) {
const img = new Image();
const url = URL.createObjectURL(file);
img.src = url;
await new Promise(r => img.onload = r);
// 讀取 EXIF (需 exifr 或 exif-js)
const exif = await exifr.parse(file);
const orientation = exif?.Orientation || 1;
let canvas, ctx;
switch (orientation) {
case 1: return img; // 正常
case 2: canvas = flipHorizontal(img); break; // 水平鏡像
case 3: canvas = rotate90(img, 2); break; // 180°
case 4: canvas = flipVertical(img); break; // 垂直鏡像
case 5: canvas = flipHorizontal(rotate90(img, 1)); break;
case 6: canvas = rotate90(img, 1); break; // 90° CW
case 7: canvas = flipHorizontal(rotate90(img, 3)); break;
case 8: canvas = rotate90(img, 3); break; // 270° CW
}
URL.revokeObjectURL(url);
return canvas;
}
function flipHorizontal(img) { /* ctx.scale(-1,1) drawImage */ }
function flipVertical(img) { /* ctx.scale(1,-1) drawImage */ }
// worker.js
self.onmessage = async e => {
const { bitmap, angle } = e.data;
const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
const ctx = canvas.getContext('2d');
// ... 旋轉邏輯同上 ...
const blob = await canvas.convertToBlob({ type: 'image/jpeg', quality: 0.9 });
self.postMessage({ blob }, [blob]);
};
// main.js
const worker = new Worker('worker.js');
const bitmap = await createImageBitmap(file);
worker.postMessage({ bitmap, angle: 90 }, [bitmap]);
worker.onmessage = e => {
const url = URL.createObjectURL(e.data.blob);
// 顯示或上傳
};
.rotated-90 { transform: rotate(90deg); }
.rotated-180 { transform: rotate(180deg); }
.rotated-270 { transform: rotate(270deg); }
/* 修正 transform-origin 防止位移 */
img { transform-origin: center center; }
/* 配合 EXIF 自動修正 (需 JS 讀取 EXIF 添加類別) */
⚠️ CSS 旋轉**不改變像素數據**,適合「顯示層」修正;「下載/上傳/編輯」必須用 Canvas/WebGL 實際重寫像素。
| 坑點 | 現象 | 解法 |
|---|---|---|
| Canvas 尺寸過大 | 超過裝置限制 (如 4096×4096) 導致空白/崩潰 | 分塊渲染、降級縮放、WebGL 無限制 |
| 圖片模糊 | 未設 `devicePixelRatio`、縮放插值 | `ctx.imageSmoothingEnabled = false` (像素風) 或 `canvas.width = cssW * dpr` |
| 跨域汙染 | `toDataURL()` / `getImageData()` 拋 SecurityError | 圖片加 `crossorigin="anonymous"`、服務端配置 CORS |
| 內存洩漏 | 大量 `createObjectURL` 未 `revokeObjectURL` | 用完即 `URL.revokeObjectURL(url)` |
| EXIF 丟失 | Canvas 輸出無 EXIF,下載後手機相簿方向錯 | 用 `piexifjs` 寫入 EXIF 到 JPEG Blob |
圖片旋轉看似簡單,**EXIF 方向修正、高 DPI 適配、跨域安全、大圖分塊、GPU 加速、Web Worker 非阻塞** 才是生產級難點。現代專案:顯示層用 CSS `transform` + EXIF 類別、編輯層用 OffscreenCanvas + Worker、高階特效用 WebGL,三層架構各司其職,效能與體驗雙贏。