Image Crossfade with JavaScript and CSS3 Transitions

Image Crossfade with Javascript and CSS3 Transitions

Since you're asking for the whole thing including CSS, here's a working demo (requires CSS3 transition-capable browser such as Chrome, Safari or Firefox 4+): http://jsfiddle.net/jfriend00/cwP5Q/.

HTML:

<div id="container">
<img id="slideimg0" class="slide showMe" src="http://photos.smugmug.com/photos/344287800_YL8Ha-S.jpg">
<img id="slideimg1" class="slide" src="http://photos.smugmug.com/photos/344287888_q22cB-S.jpg">
<img id="slideimg2" class="slide" src="http://photos.smugmug.com/photos/344284440_68L2K-S.jpg">
<img id="slideimg3" class="slide" src="http://photos.smugmug.com/photos/344286315_oyxRy-S.jpg">
<img id="slideimg4" class="slide" src="http://photos.smugmug.com/photos/344285236_hjizX-S.jpg">
</div>

CSS:

#container {position: relative; font-size: 0;}
.slide {
border: none;
opacity: 0;
position: absolute;
top: 0;
left: 0;
-webkit-transition: opacity 2s linear;
-moz-transition: opacity 2s linear;
-o-transition: opacity 2s linear;
transition: opacity 2s linear;
}
.showMe {opacity: 1;}

JS (runs when page is ready):

var timer = setInterval(nextImage, 4000);
var curImage = 0;
var numImages = 5;

function nextImage() {
var e;
// remove showMe class from current image
e = document.getElementById("slideimg" + curImage);
removeClass(e, "showMe");

// compute next image
curImage++;
if (curImage > numImages - 1) {
curImage = 0;
}

// add showMe class to next image
e = document.getElementById("slideimg" + curImage);
addClass(e, "showMe");
}

function addClass(elem, name) {
var c = elem.className;
if (c) c += " "; // if not blank, add a space separator
c += name;
elem.className = c;
}

function removeClass(elem, name) {
var c = elem.className;
elem.className = c.replace(name, "").replace(/ /g, " ").replace(/^ | $/g, ""); // remove name and extra blanks
}

If you were going to do this for real, you should use a class library like jQuery or YUI which will make animations both easier and work in all browsers, not just CSS3 capable browsers.

Background crossfade transitions javascript and css

I'm reading that you have two different issues that you are trying to solve.
The biggest issue is the crossfading issue. The other issue is the performance and loading of the images.

As this is a school assignment I think it's not a good idea to share the exact code that will make this work, but I'll give you some pointers that you can use to get to the desired result.

  1. For crossfading you will need to have 2 elements that use a fade animation (css opacity) to create the effect.
  2. Once the element that fades out is completely faded out, swap the source of the image for a new one and fade it back in while the other element fades out and repeat the process.
  3. By changing the source of the image when it's not visible for the user you will probably have a better look and feel because the image will be loaded before it's shown to the user.
  4. To get it performant, make sure that the images that you are using are as small as possible in file size. For reference I would try to keep them under a 100kb to start with.
  5. You could also look into preloading the images, but that might be a step too far for a school assignment.

Hope this helps. Good luck.

How to add transition to a changing image (with Javascript)

I would have structured it differently.

Insert the two images and give them each different class.
Using Jquery/javascript to trigger the new class which makes the transition.

$(document).ready(function() {
$("#eb_onclick").click(function() {
$("#mycontainer img.top").toggleClass("transparent");
});
});
#mycontainer {
position:relative;
height:281px;
width:450px;
margin:0 auto;
}
#mycontainer img {
position:absolute;
left:0;
-webkit-transition: opacity 1s ease-in-out;
-moz-transition: opacity 1s ease-in-out;
-o-transition: opacity 1s ease-in-out;
transition: opacity 1s ease-in-out;
}

#mycontainer img.transparent {
opacity:0;
}
#eb_onclick {
cursor:pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="eb_onclick" >Click me to toggle</button>
<div id="mycontainer" class="shadow">

<img class="bottom" height="100px" src="https://cdn.pixabay.com/photo/2018/07/26/07/45/valais-3562988_960_720.jpg" />
<img class="top" height="100px" src="https://cdn.pixabay.com/photo/2020/06/26/17/16/daisies-5343423_960_720.jpg" />
</div>

Cross-Fade Image Transition on Click

It can be done in a step-by-step process:

  1. Create an img element at the same position of the original image.
  2. Increase the z-index of said element
  3. Hide the element
  4. Add element into the DOM
  5. Fade it slowly into the view.

See the WORKING SNIPPET BELOW:

SOLN 1: using pure Javascript & filter: alpha without CSS3 for even old browsers like IE-5+:

function act() {  var element = document.createElement("img");  element.src = "http://placekitten.com.s3.amazonaws.com/homepage-samples/408/287.jpg";  var op = 0.1; // initial opacity  element.style.opacity = op;  document.body.appendChild(element);  element.style.display = 'block';  var timer = setInterval(function() {    if (op >= 1) {      clearInterval(timer);    }    element.style.opacity = op;    element.style.filter = 'alpha(opacity=' + op * 100 + ")"; // IE 5+ Support    op += op * 0.1;  }, 50);}
img {  position: absolute;  top: 30px;  left: 0px;  width: 300px;  height: 300px;}
<button onclick='act()'>FADE CHANGE</button><br /><img id="img" src="http://placekitten.com.s3.amazonaws.com/homepage-samples/200/287.jpg">

How to use @keyframes for cross-fade gallery of images in css?

JavaScript method

Basic approach:

  1. In your CSS, all pictures default to opacity: 0.
  2. In your HTML, set a class name on one of the pictures that changes that picture's opacity to 1.
  3. In JavaScript, periodically toggle that class throughout the pictures.
  4. Don't even bother with keyframes and just do our delaying in JavaScript directly. This lets you more easily modify how long you want different parts of the pulsing animation to last instead of having to calculate the percentage of the total animation-duration like you'd have to with keyframes.

const pics = document.querySelectorAll('.pic');const lastPic = pics.length - 1;const transitionDuration = 800; // matches CSSconst transitionDelay = 3000; // up to youconst totalDelay = transitionDuration + transitionDelay;const intervalDelay = (transitionDuration * 2) + transitionDelay; // time to fade out + time to fade in + time to stay active
function toggleClass() { const activePic = document.querySelector('.pic.active'); const activeIndex = Array.prototype.indexOf.call(pics, activePic); const nextIndex = activeIndex === lastPic ? 0 : activeIndex + 1; const nextPic = pics[nextIndex];
setTimeout(() => activePic.classList.remove('active'), transitionDelay); setTimeout(() => nextPic.classList.add('active'), totalDelay);}
setInterval(toggleClass, intervalDelay);
.wrapper {  width: 400px;  height: 300px;  position: relative;}.pic {  position: absolute;  top: 0;  left: 0;  width: 100%;  opacity: 0;  transition: opacity 800ms ease; /* immediately start fading out when active class is lost */}.pic.active {  opacity: 1;}
<div class="wrapper">  <img class="pic active" src="https://via.placeholder.com/400x300?text=picture%201" alt="">  <img class="pic" src="https://via.placeholder.com/400x300?text=picture%202" alt="">  <img class="pic" src="https://via.placeholder.com/400x300?text=picture%203" alt="">  <img class="pic" src="https://via.placeholder.com/400x300?text=picture%204" alt=""></div>

Smooth blend/transition between images on mousemove

The function getElement is from a jquery like library named mootools. Honestly, I have never heard of it before. I transpiled the code to plain js and attached below.

Working demo

var n = document.querySelector("#maskedImages");

if (n) {
var s = n.querySelectorAll("img")[1];
s && n.addEventListener("mousemove", function(e) {
var t = -2 * e.clientX;
s.style["-webkit-mask-position"] = t + "px 0";
s.style["mask-position"] = t + "px 0";
})
}
section#test {
background: url('https://images5.alphacoders.com/117/thumb-1920-1178361.jpg') center center/cover no-repeat;
}

section#test .masked {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 0
}

section#test .masked img {
width: 100%;
height: 100%;
object-fit: cover;
position: absolute;
left: 0;
top: 0
}

section#test .masked picture:nth-child(2) img {
-webkit-mask-image: linear-gradient(-90deg, rgba(0, 0, 0, 0) 0, #000 50%);
mask-image: linear-gradient(-90deg, rgba(0, 0, 0, 0) 0, #000 50%);
-webkit-mask-position: 0 0;
mask-position: 0 0;
-webkit-mask-repeat: no-repeat;
mask-repeat: no-repeat;
-webkit-mask-size: 200% auto;
mask-size: 200% auto
}
<section id="test">
<div class="container">
<div class="row">
<div class="col-lg-12 text-center link-danger">
testing background
</div>
</div>
</div>

<div class="masked" id="maskedImages">
<picture>
<img src="https://images4.alphacoders.com/108/thumb-1920-1082562.jpg" alt="test" />
</picture>
<picture>
<img src="https://images3.alphacoders.com/108/thumb-1920-1082567.jpg" alt="test" />
</picture>
</div>
</section>

Crossfade animation

You can handle the actual opacity transition in pure CSS itself.

Therefore, all that's left to do on the JavaScript side, is decide whether a given element we want to cycle through, should be active, or not.

// Get all matching elements, with class "cycleImage
const cycleImages = document.querySelectorAll(".cycleImage");

function cycle() {
for (let i = 0; i < cycleImages.length; i++) {
if (cycleImages[i].classList.contains('active')) {
cycleImages[i].classList.remove('active');
// If the new index we want to set to active is out of bounds, start back at the beginning
const newActive = i + 1 >= cycleImages.length ? 0 : i + 1;
cycleImages[newActive].classList.add('active');
break; // If we have already encountered our solution, we can break out of the loop early.
}
}
}

document.addEventListener("DOMContentLoaded", () => setInterval(cycle, 2000));
.cycleImage.active {
z-index: 2;
opacity: 1;
}

.cycleImage {
z-index: 0;
opacity: 0;
transition: opacity 0.2s;
/* For test display only, remove from here */
height: 100px;
width: 100px;
}

.image1 {
background-color: blue;
}

.image2 {
background-color: red;
}

.image3 {
background-color: green;
}

/* Until here */
<div class="header">
<img src="./best1.png" alt="" class="cycleImage image1 active" />
<img src="./best2.png" alt="" class="cycleImage image2" />
<img src="./best3.png" alt="" class="cycleImage image3" />
</div>


Related Topics



Leave a reply



Submit