Letter Particles With Keyboard
const Key = {
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
disabled: false
};
const keyDown = {};
function setupKeys() {
const alph = 'abcdefghijklmnopqrstuvwxyz'.split('');
const keys = {};
const aKey = 65;
alph.forEach((letter, i) => {
const idx = aKey + i;
keyDown[idx] = false;
Key[letter.toUpperCase()] = idx;
});
keyDown.allLetters = () => {
const lettersDown = alph.filter(
letter => keyDown[Key[letter.toUpperCase()]]
);
return lettersDown;
};
document.addEventListener('keydown', e => {
e.preventDefault();
if (!Key.disabled) {
keyDown[e.which] = true;
}
});
document.addEventListener('keyup', e => {
e.preventDefault();
keyDown[e.which] = false;
});
}
setupKeys();
// later:
const dots = {};
let id = 0;
function dot(letter = '') {
const el = document.createElement('div');
el.innerHTML = letter;
const size = 20;
const scale = 1 + Math.random() * 2;
const vel = (2 - scale / 2) / 4;
let x = innerWidth / 2 - size;
let y = innerHeight / 2 - size;
let vx = Math.random() * 6 - 3;
let vy = Math.random() * 6 - 3;
let life = 0;
let maxLife = Math.floor(50 + Math.random() * 30);
Object.assign(el.style, {
position: 'absolute',
left: 0,
top: 0,
transform: `translate3d(${x}px, ${y}px)`,
borderRadius: '500px',
background: 'red',
width: `${size}px`,
fontFamily: 'sans-serif',
textAlign: 'center',
color: 'white'
});
id++;
let props = {
el,
id,
right() {
vx += vel;
},
left() {
vx -= vel;
},
down() {
vy += vel;
},
up() {
vy -= vel;
},
run() {
life++;
if (life === maxLife) {
document.body.removeChild(dots[props.id].el);
delete dots[props.id];
}
x += vx;
y += vy;
vx *= 0.999;
vy *= 0.999;
el.style.transform = `translate(${x}px, ${y}px) scale(${scale}) `;
}
};
dots[id] = props;
document.body.appendChild(el);
}
function loop() {
keyDown.allLetters().forEach(letter => {
dot(letter);
});
for (let i in dots) {
dots[i].run();
}
if (keyDown[Key.LEFT]) {
for (let i in dots) {
dots[i].left();
}
}
if (keyDown[Key.DOWN]) {
for (let i in dots) {
dots[i].down();
}
}
if (keyDown[Key.RIGHT]) {
for (let i in dots) {
dots[i].right();
}
}
if (keyDown[Key.UP]) {
for (let i in dots) {
dots[i].up();
}
}
requestAnimationFrame(loop);
}
loop();
const info = document.createElement('div')
info.innerHTML = 'click here, then type letters and use arrow keys'
document.body.appendChild(info)
A demo showing how to use the keyboard snippet from yesterday. Also added a function to obtain an array of all currently pressed letter keys