There's probably some more clever ways to do things.
I offset the dance floor from the bottom and right side so I could cheat and not have to calculate when the dancers were flying off the screen. I set a faint outline so you could see it but hide that, of course. It's basically a fence for the upper-left corner of each dancer. They can't wander outside the fence.
// get the dance floor
const danceFloor = document.querySelector(".danceFloor");
// get the dancers
const dancers = danceFloor.querySelectorAll("img");
// get the dance floor dimensions
const { width, height } = getComputedStyle(danceFloor);
const { dfw, dfh } = { dfw: parseInt(width), dfh: parseInt(height) };
// set the beat
const INTERVAL = 20;
// initialize dancer vectors
dancers.forEach((dancer) => {
dancer.dataset.vx = Math.floor(Math.random() * 3 + 1);
dancer.dataset.vy = Math.floor(Math.random() * 3 + 1);
});
// after the dancers are all set...
window.onload = () =>
// start the music
setInterval(() => {
// move each dancer
dancers.forEach((dancer) => {
// get the dancer vectors
const vx = parseInt(dancer.dataset.vx);
const vy = parseInt(dancer.dataset.vy);
// get the dancers' current position
const dl = parseInt(dancer.style.left) || 0;
const dt = parseInt(dancer.style.top) || 0;
// update the position by adding the vector
dancer.style.left = `${dl + vx}px`;
dancer.style.top = `${dt + vy}px`;
// get the dancer position in the dancefloor
const { x, y } = dancer.getBoundingClientRect();
// if they are dancing off the floor, reverse direction
if (x < 0 || x > dfw) dancer.dataset.vx = -vx;
if (y < 0 || y > dfh) dancer.dataset.vy = -vy;
});
}, INTERVAL);
body {
background-color: rgba(0, 0, 0, 0.02);
}
.danceFloor {
position: absolute;
border: 1px solid rgba(0, 0, 0, 0.05);
top: 0;
left: 0;
right: 100px;
bottom: 100px;
}
.danceFloor img {
position: relative;
}
<div class="danceFloor">
<img src="https://via.placeholder.com/100/000" />
<img src="https://via.placeholder.com/100/f00" />
<img src="https://via.placeholder.com/100/0f0" />
<img src="https://via.placeholder.com/100/00f" />
<img src="https://via.placeholder.com/100/ff0" />
</div>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…