-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.js
50 lines (40 loc) · 1.49 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
document.addEventListener('DOMContentLoaded', async () => {
const images = await fetch('images.json').then(resp => resp.json());
// 全ての確率の合計を計算
const totalProbability = images.reduce((total, image) => total + image.probability, 0);
// 各画像の確率を正規化(合計が1になるように調整)
images.forEach(image => image.probability /= totalProbability);
const randomImage = document.querySelector('#randomImage');
let previousImageIndex = 0;
// 画像のプリロード
images.forEach(image => {
const img = new Image();
img.src = image.src;
});
randomImage.src = images[previousImageIndex].src;
randomImage.addEventListener('click', () => {
let newImageIndex = 0;
const randomNumber = Math.random();
let cumulativeProbability = 0;
for (let i = 0; i < images.length; i++) {
if (i === previousImageIndex) continue;
cumulativeProbability += images[i].probability;
if (randomNumber < cumulativeProbability) {
newImageIndex = i;
break;
}
}
randomImage.src = images[newImageIndex].src;
previousImageIndex = newImageIndex;
});
// スペースキーが押された時のイベントを追加
document.addEventListener('keydown', (e) => {
if (e.key === " ") { // スペースキーのイベントを検出
randomImage.click();
randomImage.classList.add('active');
setTimeout(() => {
randomImage.classList.remove('active');
}, 80);
}
});
});