イメージ(Image)
目次
- イメージオブジェクト
- image = new Image([width, height])
- window.document.images
- window.document.images.length
- window.document.images[n]
- window.document.images[id]
- window.document.image.src
- window.document.image.name
- window.document.image.width
- window.document.image.height
- window.document.image.hspace
- window.document.image.vspace
- window.document.image.border
- window.document.image.lowsrc
- window.document.image.complete
イメージオブジェクト
image = new Image([width, height])
イメージオブジェクトを生成します。width, height は省略可能で、画像の横幅、高さを指定します。後に必要となる画像データをあらかじめキャッシュに読み込んでおく際などに用いられます。
JavaScript
var img = new Image(100, 200); img.src = "./image/example.png"; document.body.appendChild(img);
window.document.images
window.document.images.length
window.document.images[n]
window.document.images[id]
images はこのドキュメントに含まれるイメージ(画像)オブジェクトの配列、length はその個数を示します。個々のイメージオブジェクトは images[id] や images[n] や for ... of で参照します。
JavaScript
// 名前(id)で参照する img = document.images["img1"]; console.log(img.src); // images[n] で参照する for (var i = 0; i < document.images.length; i++) { img = document.images[i]; console.log(img.src); } // for (...of...) で参照する for (const img of document.images) { console.log(img.src); }
window.document.image.src
window.document.image.name
window.document.image.width
window.document.image.height
window.document.image.hspace
window.document.image.vspace
window.document.image.border
window.document.image.lowsrc
それぞれ、<img> タグの画像ファイル(src)、名前(name)、横幅(width)、高さ(height)、横方向の余白(hspace)、縦方向の余白(vspace)、ボーダーの太さ(border)、読み込み中に表示する低解像度画像ファイル(lowsrc)属性に対応する値を示します。
src に画像の URL を設定することにより、表示されている画像を変更することができます。さらに Internet Explorer では、width や height などにも値を設定して大きさなどを変更することができます。
HTML
<script> if (document.images) { img1 = new Image(); // キャッシュに hidari.gif を img1.src = "hidari.gif"; // 読みこませておく。 } function setImage(name, src) { if (document.images) { document.images[name].src = src; } } </script> <img name="img1" src="migi.gif" alt="xxx"> <form action="#"> <input type="button" value="右" onclick="setImage('img1', 'migi.gif')"> <input type="button" value="左" onclick="setImage('img1', 'hidari.gif')"> </form>
window.document.image.complete
読込みが完了しているかどうかを示す真偽値を返します。
Copyright (C) 1996-2001 杜甫々
改訂版初版:2001年5月20日、最終更新:2002年2月4日
https://www.tohoho-web.com/js/image.htm