-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
263 lines (222 loc) · 9.08 KB
/
script.js
File metadata and controls
263 lines (222 loc) · 9.08 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
const bgIcons = document.querySelector(".bg-icons");
const keys = document.querySelectorAll(".key");
const icons = ["⭐", "🎵", "🎶", "✨"];
// available music files in Assets/music (enumerated from project)
const availableFiles = [
"24.mp3","29.mp3","36.mp3","41.mp3","48.mp3","53.mp3","60.mp3",
"64.mp3","65.mp3","69.mp3","72.mp3","77.mp3","79.mp3","84.mp3","96.mp3",
"metro-hi-final.mp3","metro-low-final.mp3"
];
const availableMidis = availableFiles
.map(f => parseInt(f, 10))
.filter(n => !isNaN(n));
/* Background floating icons */
for (let i = 0; i < 40; i++) {
const span = document.createElement("span");
span.innerText = icons[Math.floor(Math.random() * icons.length)];
span.style.left = Math.random() * 100 + "vw";
span.style.animationDuration = 6 + Math.random() * 10 + "s";
span.style.fontSize = 14 + Math.random() * 20 + "px";
bgIcons.appendChild(span);
}
const piano = document.querySelector('.piano');
// keyboard mapping order: numbers 1-0, then Q->P, A->L, Z->M (common piano layout)
const keyboardMap = [
'1','2','3','4','5','6','7','8','9','0',
'q','w','e','r','t','y','u','i','o','p',
'a','s','d','f','g','h','j','k','l',
'z','x','c','v','b','n','m'
];
function generateKeysToFill() {
// read sizing from CSS variables (fallbacks provided)
const styles = getComputedStyle(piano);
const whiteW = parseFloat(styles.getPropertyValue('--w')) || 72;
const gap = parseFloat(styles.getPropertyValue('--gap')) || 6;
const blackW = parseFloat(styles.getPropertyValue('--blackW')) || 46;
const paddingLeft = parseFloat(styles.paddingLeft) || 12;
// compute available width from the piano parent (piano-wrap) so keys fit inside the frame
const wrap = piano.parentElement; // .piano-wrap
const wrapStyles = wrap ? getComputedStyle(wrap) : null;
const wrapPaddingLeft = wrapStyles ? parseFloat(wrapStyles.paddingLeft) || 0 : 0;
const availableWidth = (wrap ? wrap.clientWidth : window.innerWidth) - wrapPaddingLeft * 2;
// fill the full available width of the piano-wrap so keys cover the frame
const targetWidth = availableWidth;
const keysNeeded = Math.max(7, Math.floor((targetWidth + gap) / (whiteW + gap)));
// clear existing keys and recreate
piano.innerHTML = '';
const notes = ['C','D','E','F','G','A','B'];
// helper: semitone offsets of white notes relative to C
const whiteOffsets = [0,2,4,5,7,9,11];
const baseMidi = 48; // C3
// create white keys
const whiteEls = [];
for (let i = 0; i < keysNeeded; i++) {
const k = document.createElement('div');
k.className = 'key white';
const idx = i % 7;
const octave = Math.floor(i / 7);
const midi = baseMidi + octave * 12 + whiteOffsets[idx];
k.dataset.note = notes[idx];
k.dataset.index = i;
k.dataset.midi = midi;
piano.appendChild(k);
whiteEls.push(k);
}
// create black-keys container and black keys positioned over whites
const blackContainer = document.createElement('div');
blackContainer.className = 'black-keys';
piano.appendChild(blackContainer);
const blackByWhite = {};
for (let i = 0; i < keysNeeded; i++) {
const note = notes[i % 7];
if (note === 'E' || note === 'B') continue; // no black key after E or B
const bk = document.createElement('div');
bk.className = 'key black';
bk.dataset.note = note + '#';
// derive midi: white midi + 1 semitone
const whiteIdx = i % 7;
const octave = Math.floor(i / 7);
const whiteMidi = baseMidi + octave * 12 + whiteOffsets[whiteIdx];
const midi = whiteMidi + 1;
bk.dataset.midi = midi;
// left relative to blackContainer (blackContainer left aligns with piano padding)
const left = i * (whiteW + gap) + whiteW + gap / 2 - blackW / 2;
bk.style.left = left + 'px';
blackContainer.appendChild(bk);
blackByWhite[i] = bk;
}
// build ordered left-to-right array interleaving white and black keys
const ordered = [];
for (let i = 0; i < whiteEls.length; i++) {
ordered.push(whiteEls[i]);
if (blackByWhite[i]) ordered.push(blackByWhite[i]);
}
// expose ordered keys globally for keyboard mapping
window.orderedKeys = ordered;
// re-bind interaction handlers
const keys = piano.querySelectorAll('.key');
keys.forEach(key => {
key.addEventListener('click', () => {
// use precomputed midi when available
const midi = key.dataset.midi ? parseInt(key.dataset.midi, 10) : null;
playNote(midi);
spawnParticles(key);
// floating note visual (note name, key element)
spawnFloatingNote(key.dataset.note, key);
key.classList.add('active');
setTimeout(() => key.classList.remove('active'), 450);
});
});
}
// generate on load and on resize
window.addEventListener('DOMContentLoaded', () => generateKeysToFill());
window.addEventListener('resize', () => {
// debounce resize
clearTimeout(window._pianoResize);
window._pianoResize = setTimeout(() => generateKeysToFill(0.7), 120);
});
// keyboard -> piano mapping
window.addEventListener('keydown', (e) => {
const active = document.activeElement;
if (active && (active.tagName === 'INPUT' || active.tagName === 'TEXTAREA' || active.isContentEditable)) return;
const key = (e.key || '').toLowerCase();
const mapIndex = keyboardMap.indexOf(key);
if (mapIndex === -1) return;
const ordered = window.orderedKeys || [];
if (mapIndex >= ordered.length) return; // unmapped if piano too small
const target = ordered[mapIndex];
if (!target) return;
// simulate click
target.click();
e.preventDefault();
});
function playNote(midi) {
// midi may be null or numeric. Find closest available midi sample.
if (!midi) return;
let closest = availableMidis[0];
let bestDiff = Math.abs(midi - closest);
for (const m of availableMidis) {
const diff = Math.abs(midi - m);
if (diff < bestDiff) {
bestDiff = diff;
closest = m;
}
}
const filename = `${closest}.mp3`;
const path = `Assets/music/${filename}`;
const audio = new Audio(path);
audio.currentTime = 0;
audio.play().catch(()=>{});
}
function spawnParticles(key) {
for (let i = 0; i < 6; i++) {
const span = document.createElement("span");
span.classList.add("particle");
span.innerText = icons[Math.floor(Math.random() * icons.length)];
const rect = key.getBoundingClientRect();
span.style.left = rect.left + rect.width / 2 + "px";
span.style.top = rect.top + "px";
span.style.setProperty("--x", `${(Math.random() - 0.5) * 200}px`);
span.style.setProperty("--y", `${-Math.random() * 200}px`);
document.body.appendChild(span);
setTimeout(() => span.remove(), 1200);
}
}
/**
* Spawn a floating note label above a key.
* Accepts a note name (string) and either a DOM element for the key
* or a bounding box {left, top, width, height}.
*/
function spawnFloatingNote(noteName, keyOrRect) {
try {
const wrap = piano.parentElement; // .piano-wrap
if (!wrap) return;
// prefer the global top overlay if present, otherwise fall back to piano-wrap overlay
const globalOverlay = document.querySelector('.floating-notes-top');
const overlay = globalOverlay || wrap.querySelector('.floating-notes');
if (!overlay) return;
let keyRect;
if (keyOrRect && keyOrRect.getBoundingClientRect) {
keyRect = keyOrRect.getBoundingClientRect();
} else if (keyOrRect && typeof keyOrRect === 'object') {
keyRect = keyOrRect; // assume has left, top, width, height
} else {
// if no key rect provided, still show centered top note
keyRect = wrap.getBoundingClientRect();
}
const wrapRect = wrap.getBoundingClientRect();
const overlayRect = overlay.getBoundingClientRect();
// create element
const el = document.createElement('div');
el.className = 'floating-note';
el.textContent = noteName;
// Position the floating note centered horizontally over the piano-frame
const pianoFrame = document.querySelector('.piano-frame');
const frameRect = pianoFrame ? pianoFrame.getBoundingClientRect() : wrapRect;
const centerX = frameRect.left + (frameRect.width / 2) - overlayRect.left;
// Spread multiple quick notes horizontally around center so they don't overlap.
const existingAll = Array.from(overlay.querySelectorAll('.floating-note'));
const index = existingAll.length; // 0 = first note (center)
const spacing = 72; // px between notes horizontally
// alternating offsets: 0, +1, -1, +2, -2, ...
let offsetX = 0;
if (index > 0) {
const k = Math.ceil(index / 2);
const dir = (index % 2 === 1) ? 1 : -1; // odd => right, even => left
offsetX = dir * k * spacing;
}
const startTop = Math.max(12, frameRect.top - overlayRect.top - 80); // vertical position above piano
el.style.left = `${centerX + offsetX}px`;
el.style.top = `${startTop}px`;
overlay.appendChild(el);
// force reflow then animate
requestAnimationFrame(() => el.classList.add('animate'));
// remove after animation end
const remove = () => { el.remove(); };
el.addEventListener('animationend', remove, { once: true });
// safety cleanup
setTimeout(remove, 1600);
} catch (e) {
console.error('spawnFloatingNote error', e);
}
}