Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we get the real image size through the canvas?

Tags:

html

image

canvas

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?

like image 356
LittleFunny Avatar asked Feb 03 '12 12:02

LittleFunny


1 Answers

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?

like image 171
Simon Sarris Avatar answered Nov 15 '22 07:11

Simon Sarris