首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

HTML5 Canvas 圖片旋轉 90 度無效果?變換矩陣與繪製原點詳解

     編輯:程式設計綜合問答

問題代碼分析

function toChange() {
    switch(iNow) {
        case 1:
            oC.width = obj.height; oC.height = obj.width;
            oGC.rotate(90*Math.PI/180);
            oGC.drawImage(obj, 0, -obj.height);
            break;
    }
}

點擊按鈕 `iNow++` 觸發 `toChange()`,但畫布無變化。

核心誤區

  1. Canvas 狀態未重置:每次點擊在同一 `CanvasRenderingContext2D` 上疊加旋轉,且寬高交換邏輯僅執行一次(`case 1`),後續 `case 2/3/4` 缺失。
  2. 繪製原點錯誤:`rotate()` 以畫布左上角 (0,0) 為中心旋轉,圖片需先 `translate` 到中心再旋轉,或計算旋轉後左上角座標。
  3. 寬高交換時機:設置 `canvas.width/height` 會清空畫布並重置變換矩陣,需在繪製前完成。

標準旋轉 90° 實現

function drawRotated(img, angle) {
    const canvas = document.getElementById('myCanvas');
    const ctx = canvas.getContext('2d');
    // 1. 計算旋轉後尺寸
    const rad = angle * Math.PI / 180;
    const sin = Math.abs(Math.sin(rad)), cos = Math.abs(Math.cos(rad));
    const newW = img.width * cos + img.height * sin;
    const newH = img.width * sin + img.height * cos;
    canvas.width = newW; canvas.height = newH; // 重置變換
    // 2. 平移到中心
    ctx.translate(newW/2, newH/2);
    // 3. 旋轉
    ctx.rotate(rad);
    // 4. 繪製(以圖片中心為原點)
    ctx.drawImage(img, -img.width/2, -img.height/2);
}

按鈕事件綁定修正

let angle = 0;
document.getElementById('btnRight').onclick = () => {
    angle = (angle + 90) % 360;
    drawRotated(imageObj, angle);
};

進階提示

  • 多次旋轉累積誤差:每次基於原始 `Image` 對象重繪,而非基於已旋轉的 Canvas。
  • 性能優化:離屏 Canvas 緩存旋轉結果,避免重複計算。
  • EXIF 方向:手機拍攝照片含 Orientation 標籤,顯示前需讀取並修正(使用 `exif-js` 庫)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved