6

In image tag, if we don't supply width and height property, we will get nothing when retrieving the width and the height of the image. I am using the canvas element to load an image and scale it proportionally. In order to do this, I have to get the actual image size. Is it possible to do that in html 5?

Phrogz
  • 296,393
  • 112
  • 651
  • 745
LittleFunny
  • 8,155
  • 15
  • 87
  • 198

4 Answers4

14

The HTMLImageElement has two properties for this, naturalWidth and naturalHeight. Use those.

As in:

var img = new Image();

img.addEventListener('load', function() {
  // once the image is loaded:
  var width = img.naturalWidth; // this will be 300
  var height = img.naturalHeight; // this will be 400
  someContext.drawImage(img, 0, 0, width, height);
}, false);

img.src = 'http://placekitten.com/300/400'; // grab a 300x400 image from placekitten

It is wise to set source only after the event listener is defined, see Phrogz's exploration on that here: Should setting an image src to data URL be available immediately?

Community
  • 1
  • 1
Simon Sarris
  • 62,212
  • 13
  • 141
  • 171
4

You cannot retrieve width/height before image has been loaded.

Try something like:

// create new Image or get it right from DOM, 
// var img = document.getElementById("myImage");
var img = new Image();

img.onload = function() { 
  // this.width contains image width 
  // this.height contains image height
}

img.src = "image.png";

Anyhow onload will not fire if image has been loaded before script execution. Eventually you can embed script in html <img src="test.jpg" onload="something()">

rezoner
  • 1,907
  • 13
  • 16
1

if I understand you correctly, you can use the getComputedStyle method.

var object = document.getElementById(el);
var computedHeight = document.defaultView.getComputedStyle(object, "").getPropertyValue("width"); 
Phrogz
  • 296,393
  • 112
  • 651
  • 745
tnt-rox
  • 5,400
  • 2
  • 38
  • 52
-1

Not fully understood your question.

But you can use javascript to get the width and height of the image.

and then pass it into

 / Five arguments: the element, destination (x,y) coordinates, and destination 
// width and height (if you want to resize the source image).
 context.drawImage(img_elem, dx, dy, dw, dh);

while drawing image on canvas.

or check this if it helps

http://jsfiddle.net/jjUHs/

abhinav pratap
  • 623
  • 8
  • 15