Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
67 lines (52 loc) · 1.63 KB
/
Copy pathscript.js
File metadata and controls
67 lines (52 loc) · 1.63 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
const imageElement = document.getElementById('randomImage');
const button = document.getElementById('imageButton');
let images = [];
let currentIndex = -1;
let changing = false;
async function loadManifest() {
try {
const response = await fetch('images.json', { cache: 'no-store' });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
if (!Array.isArray(data) || data.length === 0) {
throw new Error('images.json пустой');
}
images = data.filter(Boolean);
showRandomImage(false);
} catch (error) {
console.error(error);
imageElement.alt = 'Положите изображения в папку images и обновите images.json';
}
}
function getRandomIndex() {
if (images.length <= 1) return 0;
let nextIndex;
do {
nextIndex = Math.floor(Math.random() * images.length);
} while (nextIndex === currentIndex);
return nextIndex;
}
function showRandomImage(animated = true) {
if (images.length === 0 || changing) return;
const nextIndex = getRandomIndex();
const nextSrc = `images/${encodeURIComponent(images[nextIndex])}`;
if (!animated) {
currentIndex = nextIndex;
imageElement.src = nextSrc;
return;
}
changing = true;
imageElement.classList.add('is-changing');
window.setTimeout(() => {
currentIndex = nextIndex;
imageElement.src = nextSrc;
imageElement.onload = () => {
requestAnimationFrame(() => {
imageElement.classList.remove('is-changing');
changing = false;
});
};
}, 180);
}
button.addEventListener('click', () => showRandomImage(true));
loadManifest();