-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
59 lines (53 loc) · 2.21 KB
/
script.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
51
52
53
54
55
56
57
58
59
document.addEventListener('DOMContentLoaded', () => {
const inputScreen = document.getElementById('input-screen');
const resultScreen = document.getElementById('result-screen');
const userInput = document.getElementById('user-input');
const generateBtn = document.getElementById('generate-btn');
const robotImage = document.getElementById('robot-image');
const downloadBtn = document.getElementById('download-btn');
const tryAgainBtn = document.getElementById('try-again-btn');
const styleButtons = document.querySelectorAll('.style-btn');
let selectedStyle = null;
generateBtn.addEventListener('click', () => {
const inputValue = userInput.value.trim();
if (inputValue) {
const imageUrl = `https://robohash.org/${inputValue}${selectedStyle ? `?set=${selectedStyle}` : ''}`;
robotImage.src = imageUrl;
robotImage.onload = () => {
inputScreen.classList.remove('active');
resultScreen.classList.add('active');
};
} else {
alert('Please enter something to generate an avatar.');
}
});
styleButtons.forEach(button => {
button.addEventListener('click', () => {
styleButtons.forEach(btn => btn.classList.remove('selected'));
button.classList.add('selected');
selectedStyle = button.dataset.set;
});
});
downloadBtn.addEventListener('click', async () => {
try {
const response = await fetch(robotImage.src);
const blob = await response.blob();
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = 'cyberavatar.png';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
} catch (error) {
console.error('Error downloading image:', error);
}
});
tryAgainBtn.addEventListener('click', () => {
resultScreen.classList.remove('active');
inputScreen.classList.add('active');
userInput.value = '';
robotImage.src = '';
});
});