LoginSignup
36

More than 5 years have passed since last update.

posted at

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

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';

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
What you can do with signing up
36