Animación aleatoria de imágenes en JavaScript

Tiempo de ejecución: 30 minutos. Empezar

Autor: FlorinPop17
Views Total: 2,032
Sitio oficial: Ir a la web
Actualizado: September 19, 2017
Licencia: MIT

Vista prévia

Animación aleatoria de imágenes en JavaScript

Descripción

Una animación aleatoria de imágenes aleatorias implementada en JavaScript y CSS puros.

Funcionamiento

Cree un contenedor en el que desee colocar la imagen de barajado.

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

Cree un elemento de alternancia para volver a realizar/restablecer la animación aleatoria.

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

El principal JavaScript para activar la animación aleatoria. No se olvide de reemplazar la imagen con su propietario.

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);
});

Te puede interesar: