Skip to content
Advertisement

Have small images moving around independently inside a div

I have a div, about 500px x 300px and that has 5 small img inside it, I’m wondering if there is a function or animation or something that I could apply, so that all 5 images would be dancing around moving around independently of each other continually, I’ve tried translateX / Y with a random number but then they all move the same direction on the same path… Think of the game Pong, but each img is a Pong Ball bouncing of walls randomly!

Advertisement

Answer

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>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement