首页 > 解决方案 > 让小图像在 div 内独立移动

问题描述

我有一个 div,大约 500px x 300px,里面有 5 个小 img,我想知道是否有一个功能或动画或我可以应用的东西,这样所有 5 个图像都会独立地四处跳舞其他不断,我用随机数尝试了 translateX / Y 但它们都在同一条路径上移动相同的方向......想想乒乓球游戏,但每个 img 都是随机弹跳墙壁的乒乓球!

标签: javascriptcssreactjsstyled-components

解决方案


可能有一些更聪明的方法来做事。

我从底部和右侧偏移了舞池,这样我就可以作弊,而不必计算舞者何时飞离屏幕。我设置了一个模糊的轮廓,所以你可以看到它,但当然可以隐藏它。它基本上是每个舞者左上角的栅栏。他们不能在栅栏外游荡。

// 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>


推荐阅读