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
  • 271,922
  • 98
  • 616
  • 693
LittleFunny
  • 7,205
  • 11
  • 71
  • 166

4 Answers4

11

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
  • 58,131
  • 13
  • 128
  • 161
3

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,773
  • 12
  • 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
  • 271,922
  • 98
  • 616
  • 693
tnt-rox
  • 4,884
  • 2
  • 32
  • 51
0

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
  • 562
  • 7
  • 15