我有一个函数来获取图像尺寸。我发送从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