ElSaltoWeb.es Frontend Developers

ESWESW

Creando un Efecto de Rastro de Imágenes en tu Sitio Web

				
					
  <body>
    <header class="header">
      <div>
        <h2 class="person__name">ElSaltoWeb
          <span class="person__prof">Frontend Developer</span>
        </h2>
      </div>
        </header> <!-- .header -->
    <main class="content">
      <h3 class="content__title">ESWESW</h3>
      <div class="img-wrapper">
        <img decoding="async" class="img-item" src="https://elsaltoweb.es/wp-content/uploads/2024/02/alvafusion.jpg" >
        <img decoding="async" class="img-item" src="https://elsaltoweb.es/wp-content/uploads/2024/02/tusernatural.jpg" >
        <img decoding="async" class="img-item" src="https://elsaltoweb.es/wp-content/uploads/2024/02/foto-perfil.jpg" >
        <img decoding="async" class="img-item" src="https://elsaltoweb.es/wp-content/uploads/2024/02/beneficios-difusores.jpg" >
        <img decoding="async" class="img-item" src="https://elsaltoweb.es/wp-content/uploads/2024/05/andres-1-scaled.webp" >
        <img decoding="async" class="img-item" src="https://elsaltoweb.es/wp-content/uploads/2024/04/Captura-de-pantalla-2024-04-16-112711.png" >
        <img decoding="async" class="img-item" src="https://res.cloudinary.com/dtmzwq2ua/image/upload/v1567568499/12_iif68c.jpg" >
        <img decoding="async" class="img-item" src="https://elsaltoweb.es/wp-content/uploads/2024/03/Default_a_fotorrealistic_wordpress_central_offices_0.png" >
        <img decoding="async" class="img-item" src="https://elsaltoweb.es/wp-content/uploads/2024/05/limon-scaled.jpeg" >
        <img decoding="async" class="img-item" src="https://elsaltoweb.es/wp-content/uploads/2024/05/paella-scaled.jpeg" >
        <img decoding="async" class="img-item" src="https://elsaltoweb.es/wp-content/uploads/2024/05/sombrillas-scaled.jpeg" >

      </div> <!-- .img-wrapper -->

    </main><!-- .content -->
<script>
    
  const imgWrapper = document.querySelector(".img-wrapper");
const allImages = [...imgWrapper.querySelectorAll("img")];

let imgNum = 0;
// setting threshold to make a gab between images
const threshold = 125;

let lastPosX, lastPosY, curPosX, curPosY;
let isCounting = true;
let startFromX, startFromY;

document.body.addEventListener("mousemove", function(e) {
  const [x, y] = [e.x, e.y];

  const hasCrossedThresHold = // Boolean value wheather the mouse has crossed the theshold or not
    x > startFromX + threshold ||
    x < startFromX - threshold ||
    y > startFromY + threshold ||
    y < startFromY - threshold;

  if (hasCrossedThresHold) {
    // if it has calling showNextImage
    showNextImage(e);
    isCounting = true; // changing the isCounting to true
  }

  if (isCounting) {
    // So that we can record the another point here again !!
    startFromX = x;
    startFromY = y;
  }

  isCounting = false; // Changing the isCounting to false to not let recording the startFromX and
  //startFromY points on every mouse-move
});

function showNextImage(e) {
  const movingImage = allImages[imgNum];
  [curPosX, curPosY] = [e.x, e.y];

  movingImage.removeAttribute = "style";

  // Setting the position of image
  movingImage.style.left = `${curPosX}px`;
  movingImage.style.top = `${curPosY}px`;

  // making the image visibile here
  movingImage.classList.add("visible");

  // calculating a moving distance
  const movingDistanceX = ((curPosX - lastPosX || 0) * 80) / 100;
  const movingDistanceY = ((curPosY - lastPosY || 0) * 80) / 100;

  setTimeout(function() {
    // animating image towards the current position of mouse
    movingImage.style.left = `${lastPosX + movingDistanceX}px`;
    movingImage.style.top = `${lastPosY + movingDistanceY}px`;

    setTimeout(function() {
      movingImage.classList.add("grow-scale"); // hiding image after 800ms

      setTimeout(function() {
        movingImage.classList.remove("visible", "grow-scale");
        movingImage.style = "";
      }, 600);
    }, 800);
  }, 10);

  imgNum++; // incresing num to show different image  each time

  if (imgNum === allImages.length - 1) {
    imgNum = 0;
  }

  // Setting the last position values of image
  lastPosX = curPosX;
  lastPosY = curPosY;
}
</script> 

  </body>


				
			

Comprendiendo el Código

Antes de profundizar en el código, echemos un vistazo a cómo funciona este efecto:

  1. Inicialización de Elementos: El HTML contiene un contenedor de imágenes (<div class="img-wrapper">) con una serie de imágenes dentro de él.

  2. Detectando el Movimiento del Ratón: En el script JavaScript, se añade un evento de escucha al cuerpo del documento para detectar los movimientos del ratón.

  3. Generando el Efecto de Rastro: Cuando el ratón se mueve, se verifica si ha cruzado un umbral predefinido. Si es así, se activa la función showNextImage() para mostrar una imagen en la posición del ratón.

  4. Animando la Imagen: La función showNextImage() mueve la imagen hacia la posición actual del ratón con una pequeña animación. Luego, oculta la imagen y la restablece después de un breve período de tiempo.

Añade el CSS personalizado a tu widget

				
					/********************************************
ImageTrailEffects/ 
********************************************/

body {
  font-family: quiroh, sans-serif;
  font-size: 16px;

  /****** variables  *****/
  --color-pink: #d02d55;
  --color-title: #232323;
}

/***********  Default/reset  ***********/
*,
*::after,
*::before {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

/***********  Link  ***********/


.header {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  display: flex;
  z-index: 9;
  padding: 70px 30px;
  justify-content: space-between;
}

.person__name {
  color: #fff;
}

.person__prof {
  font-size: 18px;
  display: block;
  display: flex;
  align-items: center;
  font-weight: 300;
}

.person__prof:before {
  content: "";
  width: 15px;
  height: 1px;
  background: #fff;
  margin-right: 3px;
}



.person__test {
  display: block;
}

.img-wrapper {
  height: 118vh;
  background: #151413;
  position: relative;
  overflow: hidden;
}

.drag__box {
  height: 180px;
  width: 140px;
  position: absolute;
  transition: 0.1s all;
}

.visible {
  opacity: 1;
  visibility: visible;
}

.hidden {
  display: none;
}

img {
  object-fit: cover;
  width: 300px;
  visibility: hidden;
  transition: 0.6s ease-out all;
  position: absolute;
  max-width: 28px;
  transform: translateY(-50%);
  transform-origin: bottom;
}

.grow-scale {
  transform: scale(2);
  visibility: hidden;
  opacity: 0;
  transition: 0.5s all ease-in-out;
}

.content {
  position: relative;
  overflow: hidden;
  height: 118vh;
}
.content__title {
  font-family: forma-djr-display, sans-serif;
  font-size: 27vw;
  color: transparent;
  -webkit-text-stroke: 2px var(--color-title);
  font-weight: 700;
  position: absolute;
  left: 0;
  top: 60%;
  z-index: 99;
  transform: translateY(-50%);
  pointer-events: none;
}





				
			

Con solo un poco de HTML CSS y JavaScript, puedes agregar un fascinante efecto de rastro de imágenes a tu sitio web. ¡Experimenta con diferentes imágenes y ajusta los parámetros para lograr el efecto deseado!

Este efecto seguramente impresionará a tus visitantes y agregará un toque de interactividad a tu sitio web.

¡Diviértete creando y explorando! 🚀

COMPARTIR EN:
Facebook
LinkedIn
WhatsApp

Módulo 1: Fundamentos Avanzados de UI

Comprender y aplicar principios de diseño
COMPARTIR EN:
Facebook
LinkedIn
WhatsApp

Image Accordion Slider with CSS and JS

🚀 Efecto accordion slider 🖼️ que combina imágenes con animaciones suaves y diseño interactivo.💻🔥
COMPARTIR EN:
Facebook
LinkedIn
WhatsApp

¿Qué es View Transitions?

View Transitions es una API moderna del navegador que permite crear transiciones fluidas entre diferentes vistas o estados de una página web.
COMPARTIR EN:
Facebook
LinkedIn
WhatsApp

Creando partículas controladas por audio en Three.js

👉 Con tecnología de Three.js y Web Audio API, ahora el sonido no solo se escucha, ¡se ve en tiempo real! 💻🎶
COMPARTIR EN:
Facebook
LinkedIn
WhatsApp

Looping words with GSAP

CodePen Looping words with GSAP
COMPARTIR EN:
Facebook
LinkedIn
WhatsApp

WordPress con React y Gutenberg

Crear una landing page con React y Gutenberg en WordPress es una combinación poderosa para lograr una experiencia de usuario moderna y un control total sobre el desarrollo.

CONTACTO

mis redes sociales

Elsaltoweb.es

Gracias por tu confianza