Image Shuffle Animation In JavaScript

Category: Animation , Javascript | September 19, 2017
Author:FlorinPop17
Views Total:5,807 views
Official Page:Go to website
Last Update:September 19, 2017
License:MIT

Preview:

Image Shuffle Animation In JavaScript

Description:

A random image shuffle animation implemented in pure JavaScript and CSS.

How to use it:

Create a container in which you want to place the shuffled image.

<div id="container"></div>

Create a toggle element to re-perform/reset the shuffle animation.

<button class="reset">Shuffle</button>

The main JavaScript to activate the shuffle animation. Don’t forget to replace the image with your owns.

const cnt = document.getElementById('container');
const reset = document.querySelector('.reset');
const img = "https://unsplash.it/1900/1680/?random";
const n = 10;
const m = 10;
const pos = [];
const shuffled = [];
cnt.style.width = '100vw';
cnt.style.height = '100vh';

for(let i=0; i<n; i++){
  for(let j=0; j<m; j++){
    let x = i * 10;
    let y = j * 10;
    pos.push([x, y]);
    shuffled.push([x, y]);
  }
}
shuffle(shuffled);
for(let i=0; i<n; i++){
  for(let j=0; j<m; j++){
    let box = document.createElement("div");
    let x = pos[10 * i + j][0];
    let y = pos[10 * i + j][1];
        let bx = shuffled[10 * i + j][0];
        let by = shuffled[10 * i + j][1];
    box.classList.add('box');
    box.style.left = `${x}vw`;
    box.style.top = `${y}vh`;
    box.style.width = '10.2vw';
    box.style.height = '10.2vh';
    box.style.background = `url("${img}")`;
    box.style.backgroundPosition = `${-bx}vw ${-by}vh`;
    box.style.backgroundSize = '100vw 100vh';
    cnt.appendChild(box);
  }
}
setTimeout(() => {
  const boxes = document.querySelectorAll('.box');
  boxes.forEach((box, idx) => {
    box.style.left = `${shuffled[idx][0]}vw`;
    box.style.top = `${shuffled[idx][1]}vh`;
  });
}, 1500);
function shuffle(array) {
  var i = 0
  , j = 0
  , temp = null
  for (i = array.length - 1; i > 0; i -= 1) {
    j = Math.floor(Math.random() * (i + 1))
    temp = array[i]
    array[i] = array[j]
    array[j] = temp
  }
}

reset.addEventListener('click', () => {
  const boxes = document.querySelectorAll('.box');
  
  boxes.forEach((box, idx) => {
    box.style.left = `${pos[idx][0]}vw`;
    box.style.top = `${pos[idx][1]}vh`;
  });
  
  setTimeout(() => {
    boxes.forEach((box, idx) => {
      box.style.left = `${shuffled[idx][0]}vw`;
      box.style.top = `${shuffled[idx][1]}vh`;
    });
  }, 2500);
});

You Might Be Interested In:


Leave a Reply