JSFiddle - React, Tailwind, and code Playground
by azlar chen
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<h2>
Press SPACE to add line, BACKSPACE to remove line
</h2>
<div id='t'></div>
</body>
</html>
CSS
body {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
h2 {
position: absolute;
left: 12px;
top: 12px;
}
#t {
width: 200px;
height: 200px;
/* background-color: rgba(0,0, 255, .3); */
box-sizing: border-box;
border-radius: 100px;
animation: test 10s infinite linear;
position: relative;
animation-play-state: paused;
}
#t.active {
animation-play-state: running;
}
@keyframes test {
from {
transform: rotate(0deg)
}
to {
transform: rotate(360deg)
}
}
.line {
height: 2px;
width: 100px;
transform-origin: 0 0 0;
position: absolute;
top: 50%;
left: 50%;
border-radius: 5px;
transition: opacity .2s, background-color .2s;
}
#t.active .line:last-child {
transition: none;
}
JavaScript
function randomColor(){
return `rgba(${Math.round(Math.random(0,1) * 255)}, ${Math.round(Math.random(0,1) * 255)}, ${Math.round(Math.random(0,1) * 255)}, ${1})`;
}
(function (){
const PIECE_COUNT = 36;
let d = document.getElementById('t');
let children = [];
for (let i = 1;i <= PIECE_COUNT;i++) {
let line = document.createElement('div');
line.classList.add('line');
line.style.transform = `rotate(${ i * (360 / PIECE_COUNT) }deg) translateX(30px)`;
line.style.backgroundColor = randomColor();
line.style.opacity = 0;
children.push(line);
d.appendChild(line);
}
let nextActiveIndex = 0;
window.addEventListener('keydown', e => {
nextActiveIndex = Math.max(0, Math.min(PIECE_COUNT - 1, nextActiveIndex));
if (e.keyCode === 32) {
if (children[nextActiveIndex]) {
children[nextActiveIndex].style.opacity = 1;
children[nextActiveIndex].style.backgroundColor = randomColor();
nextActiveIndex++;
}
if (nextActiveIndex === PIECE_COUNT) {
setTimeout(() => {
d.classList.add('active')
// nextActiveIndex = 1;
}, 500);
}
}
if (e.keyCode === 8) {
d.classList.remove('active');
if (children[nextActiveIndex]) {
children[nextActiveIndex].style.opacity = 0;
children[nextActiveIndex].style.backgroundColor = randomColor();
nextActiveIndex--;
}
}
console.log(e.keyCode, nextActiveIndex);
})
}())