img.width 回傳的是顯示尺寸(受 CSS/width 屬性影響),非原始檔案尺寸。
var img = document.querySelector('img');
console.log(img.naturalWidth, img.naturalHeight); // 原始像素尺寸
若圖片尚未載入完成,屬性為 0,需監聽 load 事件。
function getNaturalSize(img, callback) {
if (img.naturalWidth !== undefined) { // 現代瀏覽器
callback(img.naturalWidth, img.naturalHeight);
} else { // IE6-8
var clone = new Image();
clone.onload = function() {
callback(clone.width, clone.height);
};
clone.src = img.src;
}
}
// 使用
getNaturalSize(document.querySelector('img'), function(w, h) {
console.log('原始尺寸:', w, 'x', h);
});
function getNaturalSizePromise(img) {
return new Promise(function(resolve) {
if (img.complete && img.naturalWidth) {
resolve({ width: img.naturalWidth, height: img.naturalHeight });
} else {
img.onload = function() {
resolve({ width: img.naturalWidth, height: img.naturalHeight });
};
// 處理快取情況:若已完整載入但 onload 不再觸發
if (img.complete) img.onload();
}
});
}
// 使用
getNaturalSizePromise(img).then(function(size) {
console.log(size.width, size.height);
});
Image() 不需加入 DOM 即可觸發下載與解碼。Access-Control-Allow-Origin 且 img.crossOrigin = 'anonymous',否則 naturalWidth 可能為 0(污染畫布)。naturalWidth 為 0,需指定 width/height 屬性或 CSS 尺寸。drawImage 需原始尺寸計算縮放。