获取图像尺寸

Dam*_*ski 0 javascript image function dimensions

我在获取图像尺寸方面遇到了问题.我想知道图像的宽度和高度,而不是加载到文档中.目前我的代码如下:

 function getImageSize (path) {
  var image = new Image();
  image.name = path;
  var d = image.onload = function() {
   var w = this.width;
   var h = this.height;
   return {width : w, height : h};
  }();
  image.src = path;
  return d;
 }
Run Code Online (Sandbox Code Playgroud)

如果我调用该函数,我会在两个索引(w,h)中得到包含undefined的对象.我试过不通过排除括号(8行)调用onload处理程序,但我得到的是功能代码.

请注意,如果我alert(w)在onload处理程序体内调用,我可以看到图片的宽度,但不在外面.

有人知道如何解决这个问题吗?我怎样才能获得图像尺寸?

Fel*_*ing 6

这个块

var d = image.onload = function() {
   var w = this.width;
   var h = this.height;
   return {width : w, height : h};
}();
Run Code Online (Sandbox Code Playgroud)

看起来非常腥.这实际上是立即执行函数并将对象分配{width : w, height : h}image.onloadd.wh将包含的宽度和高度窗口,因为this将参考window.

您必须将功能分配给image.onload,而不是执行它.您必须分配该功能的原因是加载图像需要一些时间,并且一旦加载图像就会调用回调.整个过程是异步的.这也意味着您无法返回图像的尺寸getImageSize.你必须让它接受一个你必须在load回调中调用的回调.

例如:

function getImageSize (path, callback) {
  var image = new Image();
  image.name = path;
  image.onload = function() {
   callback({width : this.width, height : this.height};
  }
  image.src = path;
};
Run Code Online (Sandbox Code Playgroud)

并调用该函数

getImageSize('path/to/image', function(dim) {
    // do something with dim.width, dim.height
});
Run Code Online (Sandbox Code Playgroud)

看看我的答案的第一部分,了解同步和异步代码的区别,以及回调的作用.