Get the real width and height of an image with JavaScript? (in Safari/Chrome)

后端 未结 30 2894
傲寒
傲寒 2020-11-22 01:16

I am creating a jQuery plugin.

How do I get the real image width and height with Javascript in Safari?

The following works with Firefox 3, IE7 and Opera 9:

30条回答
  •  我在风中等你
    2020-11-22 01:35

    I've done some workaround utility function, using imagesLoaded jquery plugin: https://github.com/desandro/imagesloaded

                function waitForImageSize(src, func, ctx){
                    if(!ctx)ctx = window;
                    var img = new Image();
                    img.src = src;
                    $(img).imagesLoaded($.proxy(function(){
                        var w = this.img.innerWidth||this.img.naturalWidth;
                        var h = this.img.innerHeight||this.img.naturalHeight;
                        this.func.call(this.ctx, w, h, this.img);
                    },{img: img, func: func, ctx: ctx}));
                },
    

    You can use this by passing url, function and its context. Function is performed after image is loaded and return created image, its width and height.

    waitForImageSize("image.png", function(w,h){alert(w+","+h)},this)
    

提交回复
热议问题