LoginSignup
40
36

More than 5 years have passed since last update.

imageのサイズを取得する際の注意

Posted at

Javascriptでimageの幅と高さを取得したい場合、
cssが当たっているとオリジナル画像のサイズを取得することができない。

FirefoxやSafariでは naturalWidth や naturalHeight といったプロパティが用意されているが、
クロスブラウザで使うことができない。

従って、オリジナル画像のサイズを取得するには、
一時的にimageに対するcssを解除 (widthとheightをautoに ) してから取得するか、

新たに Imageオブジェクトを生成して取得する必要がある。

var image = new Image();
var width;
var height;

image.onload = function(){
  width = image.width;
  height = image.height;
};
image.src = 'hogehoge.jpg';

40
36
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
40
36