前端顯示圖片時,常需在固定容器內等比例縮放,避免變形。本文解析經典 DrawImage 函式邏輯,並提供現代 CSS 替代方案。
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 即可實現等比縮放,效能更好、無 JS 依賴、支援響應式:
<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 填滿 */
}
.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>
<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 |
| 需支援 IE11 | Flexbox 置中 + max-width:100%; max-height:100% |
| 複雜裁切/旋轉/濾鏡 | Canvas API 或 CSS Filter |
| 舊專案維護 | DrawImage 函式仍可用,但建議漸進式遷移至 CSS |
| 特性 | JS DrawImage | CSS object-fit |
|---|---|---|
| 效能 | 需等圖片載入、JS 計算、重排 | 瀏覽器原生渲染管線,零 JS 開銷 |
| 響應式 | 需監聽 resize 重新計算 | 自動適應容器尺寸變化 |
| 載入閃爍 | 易發生(縮放前可見原始尺寸) | 可用 opacity transition 平滑 |
| 瀏覽器支援 | 所有 | IE 不支援 object-fit,其餘全支援 |