img要素の naturalWidth と naturalHeight プロパティにアクセスすることで画像本来の幅/高さを取得することが可能。
HTML
<img id="test_id" src="test.png" width="100" height="50"/>
JavaScript
const imgElment = document.getElementById("test_id") ; // img要素に設定された幅/高さを表示 alert("width=" + imgElment.width + ", height=" + imgElment.height); imgElment.onload = function(ev) { // 画像本来の幅/高さを表示 alert("naturalWidth=" + imgElment.naturalWidth + ", naturalHeight=" + imgElment.naturalHeight); }
width、height ではimg要素に設定されたサイズ(上記例だと100と50)が、
naturalWidth、naturalHeight では実際の画像自身の幅/高さが取れる。
注意点として、naturalWidthとnaturalHeightは画像の読み込み完了前にアクセスすると正しい値が取得できない(0が返る)ということ。
そのためこれらのプロパティにアクセスする場合は、上記例のように onload イベントで画像の読み込み完了を待つ必要がある。
0 件のコメント:
コメントを投稿