Transición de imagen con efecto de desvanecimiento usando JavaScript

Dadas algunas imágenes y la tarea es crear una transición lenta de una imagen a otra usando Javascript.
Requisito previo: en este artículo, utilizaremos los siguientes métodos de JavaScript. 
 

Enfoque: dadas algunas imágenes y la tarea es cambiar las imágenes después de intervalos regulares con un efecto de desvanecimiento o disolución. Para cambiar la imagen a intervalos regulares, utilice el método setInterval() . Mantenga las imágenes una encima de la otra y siga moviendo la imagen de arriba hacia abajo cambiando su índice z a intervalos regulares.
Para hacer la transición de la imagen con un efecto de desvanecimiento usamos la función asíncrona . Dentro de la función asincrónica, use otro método setInterval() para disminuir lentamente la opacidad de la imagen superior hasta que la opacidad se convierta en 0. Al hacer esto, la imagen superior parecerá desvanecerse lentamente. Una vez que la imagen superior se haya desvanecido por completo, muévala a la posición inferior y almacene el nuevo índice de imagen superior.
 

  • Código JavaScript: 
     

javascript

<script>
    startImageTransition();
 
    function startImageTransition() {
 
        // images stores list of all images of
        // class test. This is the list of images
        // that we are going to iterate
        var images = document.getElementsByClassName("test");
 
        // Set opacity of all images to 1
        for (var i = 0; i < images.length; ++i) {
            images[i].style.opacity = 1;
        }
 
        // Top stores the z-index of top most image
        var top = 1;
 
        // cur stores the index of the image currently
        // on top images list contain images in the
        // same order they appear in HTML code
        /* The tag with class test which appears last
           will appear on top of all the images thus,
           cur is set to last index of images list*/
        var cur = images.length - 1;
 
        // Call changeImage function every 3 second
        // changeImage function changes the image
        setInterval(changeImage, 3000);
 
        // Function to transitions from one image to other
        async function changeImage() {
 
            // Stores index of next image
            var nextImage = (1 + cur) % images.length;
 
            // First set the z-index of current image to top+1
            // then set the z-index of nextImage to top
            /* Doing this make sure that the image below
               the current image is nextImage*/
            // if this is not done then during transition
            // we might see some other image appearing
            // when we change opacity of the current image
            images[cur].style.zIndex = top + 1;
            images[nextImage].style.zIndex = top;
 
            // await is used to make sure
            // the program waits till transition()
            // is completed
            // before executing the next line of code
            await transition();
 
            // Now, the transition function is completed
            // thus, we can say that the opacity of the
            // current image is now 0
 
            // Set the z-index of current image to top
            images[cur].style.zIndex = top;
 
            // Set the z-index of nextImage to top+1
            images[nextImage].style.zIndex = top + 1;
 
            // Increment top
            top = top + 1;
 
            // Change opacity of current image back to 1
            // since zIndex of current is less than zIndex
            // of nextImage
            /* changing it's opacity back to 1 will not
               make the image appear again*/
            images[cur].style.opacity = 1;
 
            // Set cur to nextImage
            cur = nextImage;
        }
 
        /* This function changes the opacity of
        current image at regular intervals*/
        function transition() {
            return new Promise(function (resolve, reject) {
 
                // del is the value by which opacity is
                // decreased every interval
                var del = 0.01;
 
                // id stores ID of setInterval
                // this ID will be used later
                // to clear/stop setInterval
                // after we are done changing opacity
                var id = setInterval(changeOpacity, 10);
 
                // changeOpacity() decreasing opacity of
                // current image by del
                // when opacity reaches to 0, we stops/clears
                // the setInterval and resolve the function
                function changeOpacity() {
                    images[cur].style.opacity -= del;
                    if (images[cur].style.opacity <= 0) {
                        clearInterval(id);
                        resolve();
                    }
                }
            })
        }
    }
</script>
  •  
  • Código completo: 
     

HTML

<!DOCTYPE html>
<html>
 
<head>
    <meta charset="utf-8" />
    <title>
        Change Image Dynamically when User Scrolls
    </title>
 
    <style>
        body {
            text-align: center;
        }
         
        h1 {
            color: green;
        }
         
        img {
            position: absolute;
            left: 400px;
        }
    </style>
 
</head>
 
<body>
    <h1>GeeksforGeeks</h1>
    <b>A Computer Science Portal for Geeks</b>
    <div id="scroll-image">
        <img src=
"https://media.geeksforgeeks.org/wp-content/uploads/20200318142245/CSS8.png"
             class="test" />
        <img src=
"https://media.geeksforgeeks.org/wp-content/uploads/20200318142309/php7.png"
             class="test" />
        <img src=
"https://media.geeksforgeeks.org/wp-content/uploads/20200318142254/html9.png"
             class="test" />
    </div>
 
    <script>
        startImageTransition();
 
        function startImageTransition() {
            var images = document.getElementsByClassName("test");
 
            for (var i = 0; i < images.length; ++i) {
                images[i].style.opacity = 1;
            }
 
            var top = 1;
 
            var cur = images.length - 1;
 
            setInterval(changeImage, 3000);
 
            async function changeImage() {
 
                var nextImage = (1 + cur) % images.length;
 
                images[cur].style.zIndex = top + 1;
                images[nextImage].style.zIndex = top;
 
                await transition();
 
                images[cur].style.zIndex = top;
 
                images[nextImage].style.zIndex = top + 1;
 
                top = top + 1;
 
                images[cur].style.opacity = 1;
               
                cur = nextImage;
 
            }
 
            function transition() {
                return new Promise(function(resolve, reject) {
                    var del = 0.01;
 
                    var id = setInterval(changeOpacity, 10);
 
                    function changeOpacity() {
                        images[cur].style.opacity -= del;
                        if (images[cur].style.opacity <= 0) {
                            clearInterval(id);
                            resolve();
                        }
                    }
 
                })
            }
        }
    </script>
 
</body>
 
</html>
  • Producción: 
     

  •  

Nota: El intervalo de tiempo en el que las imágenes cambian debe ser mayor que el tiempo que se tarda en hacer que la opacidad de la imagen sea menor o igual a 0.
 

Publicación traducida automáticamente

Artículo escrito por Archaic y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *