LoginSignup
2
1

More than 3 years have passed since last update.

【JavaScript】画像をランダムに表示させる方法

Posted at

プログラミング勉強日記

2020年10月26日
何枚かの写真からJavaScriptを使ってランダムに1つ表示させる方法を紹介する。

方法

 表示候補の画像ファイルリストを事前に準備しておき、乱数を使って1つを選び出して表示させる。

image.png

具体的な手順
1. 表示させる可能性のある画像ファイル名をすべて配列に入れる
2. その中からアクセスされるたびに乱数を使って1枚選ぶ
3. 選んだ画像1つを表示させる

サンプルコード

JavaScript
const imageArea = document.getElementById('imageArea');
const images = ['【画像パス1】', '【画像パス2】', '【画像パス3】'];

const imageNo = Math.floor( Math.random() * images.length)
imageArea.src = images[imageNo];
HTML
<img src="【画像パス】" id='imageArea'>

参考文献

画像をランダムに表示する方法!JavaScriptで切り替え
JavaScriptで文字列や画像をランダムに表示する方法を現役エンジニアが解説【初心者向け】

2
1
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
2
1