Sunday, November 3, 2013

Native height, width of an image in jQuery

jQuery doesn't seem to provide a function for this, I guess because .nativeWidth is not consistently implemented across browsers. The reason I want to know the native width, that is, unscaled width of an image, is so that I can scale an imagemap that overlays it. Without knowing the precise ratio of the current scaling, the imagemap areas will be offset by the difference between the original area coordinates and the current positions and size of the image.

So my solution, which may not work for everyone, was to write the real image dimensions into the HTML in the first place. I did this via getimagesize in php. Then, by attaching an event handler in jQuery when the image first loads you can record the native width and height using custom attributes:

$( 'img' ).load(function() {
        $this.attr('nativew',$this.attr('width'));
        $this.attr('nativeh',$this.attr('height'));
    });
...// now retrieve them later:
w = $that.attr('nativew'),
h = $that.attr('nativeh');

Now I absolutely haven't tested this on more than Firefox and Chrome, but my hunch is that it will work on everything, because at bottom it relies on jQuery. The only problem for some will be writing the true image dimensions to the HTML. But it may not work with all image types. I used .png.

No comments:

Post a Comment