[英]Using JS is it possible to detect when new Image().src has loaded the image it references into memory?
背景:我正在嘗試獲取圖像的尺寸。
該塊成功地創建了一個新圖像並為其分配了一個圖形。 不幸的是,這不會立即發生。 當我嘗試使用naturalHeight
獲取高度時,它返回 0。
let myImage = new Image();
myImage.src = 'images/example.png';
let dimension = myImage.naturalHeight;
alert(dimension); // 0
但是,如果我使用setTimeout()
延遲此操作,它會給瀏覽器時間將其加載到 memory 並返回高度。
setTimeout(function() {
let dimension = myImage.naturalHeight;
alert(dimension); // 479
}, 1000);
問題:有沒有辦法檢測圖像參考是否已完全加載到 memory 中? 這樣我就可以在知道引用的圖像已加載后獲取naturalHeight
。
您可以監聽元素的onload
事件。
let myImage = new Image();
// Be sure to add the event listener before
// changing the image's source attribute.
myImage.onload = function() {
let dimension = myImage.naturalHeight;
alert(dimension);
};
myImage.src = 'images/example.png';
此答案中的更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.