javascript - 让小图像在 div 内独立移动
问题描述
我有一个 div,大约 500px x 300px,里面有 5 个小 img,我想知道是否有一个功能或动画或我可以应用的东西,这样所有 5 个图像都会独立地四处跳舞其他不断,我用随机数尝试了 translateX / Y 但它们都在同一条路径上移动相同的方向......想想乒乓球游戏,但每个 img 都是随机弹跳墙壁的乒乓球!
解决方案
可能有一些更聪明的方法来做事。
我从底部和右侧偏移了舞池,这样我就可以作弊,而不必计算舞者何时飞离屏幕。我设置了一个模糊的轮廓,所以你可以看到它,但当然可以隐藏它。它基本上是每个舞者左上角的栅栏。他们不能在栅栏外游荡。
// 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>
推荐阅读
- python-3.x - 如何在 Python 编程中使用 SBFEM?
- flutter - 如何在 Dart 中从泛型定义具体类型?
- linux - 链接器通过哪些规则在 ELF 可执行文件中创建段?
- python-3.x - 处理两个 CSV 文件以查找相似数据并将结果写入第三个 csv 文件
- sas - 对 SAS 输出中的列使用 proc 格式
- regex - 将某些换行符替换为等效于在键盘 NotePad++ 正则表达式上按删除键
- regex - 如何从语法中获取正则表达式
- javascript - javascript 如何根据当前的 URL 位置而不是相对的位置重写为绝对的,因为我们正在使用
? - excel - 我试图让一个按钮在两个单元格中一次执行一项操作,但出现错误
- php - simplexlsxgen 将文件保存为 xlsxxlsx