我有一个称为isPortrait的JS函数,用于确定给定照片的方向。问题是,当我调用它时,它总是返回false。但是,alert()可以完美工作,并返回照片的分辨率。我该如何解决?
function isPortrait(src) {
var is = false;
var img = new Image();
img.src = src;
img.onload = function() {
alert(img.width+"x"+img.height);
if(img.height>img.width)
{
is = true;
}
}
return is;
}
我的解决方案(使用全局变量):
window.isportrait = false;
function isPortrait(src) {
var img = new Image();
img.src = src;
img.onload = function() {
if(img.height>img.width)
{
window.isportrait = true;
}
else
{
window.isportrait = false;
}
}
}
在异步调用结束之前,该函数返回false!
我可以达到的最佳实现是JSBIN示例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<h1 id="heading">? </h1>
</body>
</html>
和javasScript代码是:
var is = false;
function isPortrait(src) {
var img = new Image();
img.src = src;
var here = img.onload = function() {
alert(img.width+"x"+img.height);
if(img.height>img.width)
{
is = true;
}
// it is here at this moment where you can get result of the
// awaited async function onload()
document.getElementById("heading").innerHTML = "is it Portrait ? " + is;
};
}
isPortrait("http://blogs.smithsonianmag.com/aroundthemall/files/2009/01/npg_portraits_nicholson_jack_2002-244x300.jpg");
编辑[使用'setInterval`的另一个更好的实现
var is = false;
var notYetLoaded = true;
function isPortrait(src){
tryLoadImage(src);
var myWaiting = setInterval(function(){
if(notYetLoaded === false){
// use the "is" boolean here
document.getElementById("heading").innerHTML = "is it Portrait ? " + is;
clearInterval(myWaiting);
}
}, 1000);
}
function tryLoadImage(src) {
var img = new Image();
img.src = src;
var here = img.onload = function() {
alert(img.width+"x"+img.height);
if(img.height>img.width)
{
is = true;
}
notYetLoaded = false;
};
}
isPortrait("http://blogs.smithsonianmag.com/aroundthemall/files/2009/01/npg_portraits_nicholson_jack_2002-244x300.jpg");
此处的代码:http : //jsbin.com/qodefuhe/1/edit
希望对您有所帮助:)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句