萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

Canvas 圖片旋轉:現代標準 API、EXIF 方向修正、高性能離屏渲染與 WebGL 升級路徑

核心 API:`CanvasRenderingContext2D.drawImage` + 變換矩陣

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
}

關鍵細節:90° 倍數優化(無插值、像素完美)

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;
}

EXIF 方向自動修正(手機拍照必須)

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 */ }

高性能:OffscreenCanvas + Web Worker (主執行緒零阻塞)

// 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);
  // 顯示或上傳
};

WebGL 升級:百萬級圖片/實時濾鏡/3D 旋轉

  • 使用 **Three.js / PixiJS / OGL** 等封裝庫。
  • 將圖片上傳為 **Texture**,矩陣變換在 GPU 完成,毫秒級處理 4K 圖片。
  • 支援 3D 旋轉、透視、後處理濾鏡 (Bloom、DOF、Color Grading)。

CSS 替代方案:純樣式旋轉(無畫質損失、GPU 加速)

.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,三層架構各司其職,效能與體驗雙贏。

copyright © 萬盛學電腦網 all rights reserved