我有一個函數來獲取圖像尺寸。我發送從createObjectURL返回。如何從此函數調用返回值?
它在取得尺寸時效果很好,但我無法取回數值。我試圖獲得這兩個值,但問題似乎是函數內有一個函數。而外部函數不知道在內部函數中設置的值。當我硬編碼一個值時,就像在下面的「qq」中一樣。所以我可以看到問題不在於回報,而在於價值。
你在這種情況下如何讀取值?
imgSrc = window.URL.createObjectURL(this.files[0]);
var imgSize = getImgSize(imgSrc);
var newWidth = imgSize.retWidth;
var newHeight = imgSize.retHeight;
alert(newWidth);
alert(newHeight);
function getImgSize(imgSrc) {
var newImg = new Image();
newImg.onload = function() {
var nHeight = newImg.height;
var nWidth = newImg.width;
//alert('The image size is ' + width + '*' + height);
}
newImg.src = imgSrc; //this must be done AFTER setting onload
return {
retWidth: nWidth,
retHeight: 'qq'
};
}
您的變量'nHeight'和'nWidth'只存在於'onload'函數的範圍內,請參見下面的答案。 –
您可以使用'Promise',請參閱[列出頁面上所有圖像的文件大小(Chrome擴展)](http://stackoverflow.com/questions/41085017/list-file-sizes-of-all-images-on -a-page-chrome-extension/41085297?s = 2 | 0.1129#41085297),[在canvas.ToBlob()異步函數之外訪問blob值)(http://stackoverflow.com/questions/42458849/access-blob -value-canvas-toblob-async-function /) – guest271314