80

所以警报给出了未定义的宽度和高度值。我认为来自 img.onload 计算的图像的 w 和 h 值没有传递给要返回的值,或者它可能在 onload 计算它们之前返回 w 和 h:

function getMeta(url){
 var w; var h;
 var img=new Image;
 img.src=url;
 img.onload=function(){w=this.width; h=this.height;};
 return {w:w,h:h}    
}

// "http://snook.ca/files/mootools_83_snookca.png" //1024x678
// "http://shijitht.files.wordpress.com/2010/08/github.png" //128x128

var end = getMeta("http://shijitht.files.wordpress.com/2010/08/github.png");
var w = end.w;
var h = end.h;
alert(w+'width'+h+'height');

如何让警报显示正确的宽度和高度?

http://jsfiddle.net/YtqXk/

4

5 回答 5

142

使用 jQuery 获取图像大小

function getMeta(url) {
    $("<img/>",{
        load: function() {
            alert( this.width +" "+ this.height );
        },
        src: url
    });
}

使用 JavaScript 获取图像大小

function getMeta(url) {   
    var img = new Image();
    img.onload = function() {
        alert( this.width +" "+ this.height );
    };
    img.src = url;
}

使用 JavaScript 获取图像大小(现代浏览器,IE9+)

function getMeta(url){   
    const img = new Image();
    img.addEventListener("load", function() {
        alert( this.naturalWidth +' '+ this.naturalHeight );
    });
    img.src = url;
}

像这样使用:getMeta( "http://example.com/img.jpg" );

https://developer.mozilla.org/en/docs/Web/API/HTMLImageElement

于 2012-07-11T23:07:18.267 回答
31

只需将回调作为参数传递,如下所示:

function getMeta(url, callback) {
    const img = new Image();
    img.src = url;
    img.onload = function() { callback(this.width, this.height); }
}
getMeta(
  "http://snook.ca/files/mootools_83_snookca.png",
  (width, height) => { alert(width + 'px ' + height + 'px') }
);

于 2014-10-13T12:02:40.327 回答
21

ES6

使用async/await您可以以类似顺序的方式执行以下getMeta功能,您可以按如下方式使用它(这与您问题中的代码几乎相同(我添加await关键字并将变量更改endimg,然后更改var为关键字) 。let您只需要从功能(运行)。getMetaawaitasync

function getMeta(url) {
    return new Promise((resolve, reject) => {
        let img = new Image();
        img.onload = () => resolve(img);
        img.onerror = () => reject();
        img.src = url;
    });
}

async function run() {

  let img = await getMeta("http://shijitht.files.wordpress.com/2010/08/github.png");

  let w = img.width;
  let h = img.height; 

  size.innerText = `width=${w}px, height=${h}px`;
  size.appendChild(img);
}

run();
<div id="size" />

Rxjs

const { race, fromEvent, map, mergeMap, of } = rxjs;

function getMeta(url) {
    return of(url).pipe(
        mergeMap((path) => {
            const img = new Image();
            let load = fromEvent(img, 'load').pipe(map(_=> img))
            let error = fromEvent(img, 'error').pipe(mergeMap((err) => throwError(() => err)));
            img.src = path;
            
            return race(load, error);
        })
    );
}


let url = "http://shijitht.files.wordpress.com/2010/08/github.png";

getMeta(url).subscribe(img=> { 
  let w = img.width;
  let h = img.height; 

  size.innerText = `width=${w}px, height=${h}px`;
  size.appendChild(img);
}, e=> console.log('Load error'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/7.5.2/rxjs.umd.min.js" integrity="sha512-wBEi/LQM8Pi08xK2jwHJNCiHchHnfcJao0XVQvkTGc91Q/yvC/6q0xPf+qQr54SlG8yRbRCA8QDYrA98+0H+hg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<div id="size" />

于 2018-06-27T13:18:42.473 回答
13

函数中的wh变量与img.onload函数中的变量不在同一范围内getMeta()。一种方法如下:

小提琴:http: //jsfiddle.net/ppanagi/28UES/2/

function getMeta(varA, varB) {
    if (typeof varB !== 'undefined') {
       alert(varA + ' width ' + varB + ' height');
    } else {
       var img = new Image();
       img.src = varA;
       img.onload = getMeta(this.width, this.height);
    }
}


getMeta("http://snook.ca/files/mootools_83_snookca.png");
于 2012-07-11T23:10:34.713 回答
0

使用 jQuery 获取图像大小
(取决于哪种格式化方法更适合您的喜好):

function getMeta(url){
    $('<img/>',{
        src: url,
        on: {
            load: (e) => {
                console.log('image size:', $(e.target).width(), $(e.target).height());
            },
        }
    });
}

或者

function getMeta(url){
    $('<img/>',{
        src: url,
    }).on({
        load: (e) => {
            console.log('image size:', $(e.target).width(), $(e.target).height());
        },
    });
}
于 2020-05-16T21:47:00.520 回答