萬盛學電腦網

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

JavaScript 圖片等比例縮放:DrawImage 函式實作詳解

前端顯示圖片時,常需在固定容器內等比例縮放,避免變形。本文解析經典 DrawImage 函式邏輯,並提供現代 CSS 替代方案。

經典 DrawImage 函式

function DrawImage(imgElement, maxWidth, maxHeight) {
    // 建立 Image 物件取得原始尺寸
    const image = new Image();
    image.src = imgElement.src;
    
    // 圖片尚未載入完成時,onload 會再次觸發
    if (image.width > 0 && image.height > 0) {
        resize(image.width, image.height);
    } else {
        image.onload = () => resize(image.width, image.height);
    }
    
    function resize(origW, origH) {
        const ratio = origW / origH;
        const containerRatio = maxWidth / maxHeight;
        
        let newW, newH;
        
        if (ratio >= containerRatio) {
            // 寬度為限制因素
            newW = Math.min(origW, maxWidth);
            newH = newW / ratio;
        } else {
            // 高度為限制因素
            newH = Math.min(origH, maxHeight);
            newW = newH * ratio;
        }
        
        imgElement.width = newW;
        imgElement.height = newH;
    }
}

使用方式

<img src="photo.jpg" alt="示範圖片" 
     onload="DrawImage(this, 300, 200)" 
     style="max-width: 300px; max-height: 200px;">

邏輯流程圖解

原始尺寸 (W, H) → 計算長寬比 ratio = W/H
                    ↓
容器限制 (maxW, maxH) → 容器比例 cRatio = maxW/maxH
                    ↓
比較 ratio 與 cRatio:
  ratio >= cRatio → 以寬度為基準縮放
  ratio < cRatio  → 以高度為基準縮放
                    ↓
計算新尺寸,不超過原始尺寸(不放大)

現代 CSS 方案(推薦)

純 CSS 即可實現等比縮放,效能更好、無 JS 依賴、支援響應式:

方案一:object-fit(最簡單)

<style>
.img-container {
    width: 300px;
    height: 200px;
    border: 1px solid #ddd;
    overflow: hidden;
}
.img-container img {
    width: 100%;
    height: 100%;
    object-fit: contain;  /* 等比縮放,完整顯示 */
    /* object-fit: cover;  等比縮放,填滿容器(可能裁切) */
}
</style>

<div class="img-container">
    <img src="photo.jpg" alt="示範">
</div>

方案二:背景圖片(裝飾性圖片)

.bg-image {
    width: 300px;
    height: 200px;
    background: url('photo.jpg') center / contain no-repeat;
    /* 或 cover 填滿 */
}

方案三:Flexbox 置中 + max-width/height

.flex-container {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 300px;
    height: 200px;
    border: 1px solid #ddd;
}
.flex-container img {
    max-width: 100%;
    max-height: 100%;
}

進階:載入狀態與錯誤處理

<img src="photo.jpg" 
     alt="示範" 
     onload="this.classList.add('loaded')"
     onerror="this.onerror=null; this.src='fallback.jpg'; this.alt='圖片載入失敗'">

<style>
    img { opacity: 0; transition: opacity 0.3s; }
    img.loaded { opacity: 1; }
</style>

響應式圖片:srcset 與 picture

<picture>
    <source media="(max-width: 480px)" srcset="photo-small.jpg">
    <source media="(max-width: 768px)" srcset="photo-medium.jpg">
    <img src="photo-large.jpg" alt="響應式圖片">
</picture>


<img src="photo.jpg" 
     srcset="photo-320w.jpg 320w, photo-640w.jpg 640w, photo-1280w.jpg 1280w"
     sizes="(max-width: 480px) 100vw, (max-width: 768px) 50vw, 33vw"
     alt="響應式">

總結建議

場景推薦方案
一般內容圖片object-fit: contain + 固定容器尺寸
背景裝飾圖片CSS background + background-size: cover/contain
需支援 IE11Flexbox 置中 + max-width:100%; max-height:100%
複雜裁切/旋轉/濾鏡Canvas API 或 CSS Filter
舊專案維護DrawImage 函式仍可用,但建議漸進式遷移至 CSS

核心差異對照

特性JS DrawImageCSS object-fit
效能需等圖片載入、JS 計算、重排瀏覽器原生渲染管線,零 JS 開銷
響應式需監聽 resize 重新計算自動適應容器尺寸變化
載入閃爍易發生(縮放前可見原始尺寸)可用 opacity transition 平滑
瀏覽器支援所有IE 不支援 object-fit,其餘全支援
copyright © 萬盛學電腦網 all rights reserved