What are the best ways to create image animations on top of other images using CSS or JavaScript?

Imagine if the first image is in black and white, while the second one is colored. How can we make the black and white image change to color after a timeout period, with an animation similar to loading progress bars? Is this achievable using CSS or JavaScript?

[Provided for clarity in response to a question by the original poster, mentioned below]

Original Poster: Could this be done with a slow linear animation, like filling water in a glass but with color appearing in the black and white image instead?

Answer №1

Begin by stacking two images on top of each other using the CSS property position: absolute;. Using background images, you can achieve this layout:

<div class="container">
  <div class="image1"></div>
  <div class="image2" id="image_resize"></div>
</div>

CSS:

.container {
  position: relative;
  width: 300px;
  height:200px;
}

.image1 {
  position: absolute;
  width: 100%;
  height: 100%;
  background-image: url(http://images.freeimages.com/images/previews/cf6/bird-1394216.jpg);
  background-repeat: no-repeat;
}

.image2 {
  position: absolute;
  height: 100%;
  background-image: url(http://images.freeimages.com/images/previews/4f3/apple-1322812.jpg);
  background-repeat: no-repeat;
}

To animate the second image, one option is to use jQuery's animate function. Alternatively, with vanilla JavaScript, you could do something like this:

var percent = 0; // This variable will track the percentage width increase

/* Execute a function every 50 milliseconds using setInterval */
var myInterval = window.setInterval(function() {
    var img = document.getElementById('image_resize');

    img.style.width = percent+"%";

    percent ++;

    if(percent > 100) {
      clearInterval(myInterval);
    }
}, 50);

Check out this live example on jsfiddle: https://jsfiddle.net/c51u6r8t/

Answer №2

To create a cool effect, overlay a black and white image on top of a colored image at full opacity and then gradually fade out the black and white image as desired.

setTimeout(function() {
  document.getElementById("container").className = "revealed";
}, 500);
#container {
  position: relative;
}

#container .overlay {
  position: absolute;
  top: 0px;
  left: 0px;
  transition: opacity 1.5s ease-in-out;
}

#container.revealed .overlay {
  opacity: 0;
}
<div id="container">
  <img src="http://www.esa.int/var/esa/storage/images/esa_multimedia/images/2003/10/soho_image_28_october_2003/10098404-2-eng-GB/SOHO_image_28_October_2003_node_full_image_2.jpg">
  <img class="overlay" src="http://dawn.jpl.nasa.gov/multimedia/images/dawn-image-070911.jpg">
</div>

Check out this Fiddle for a live demo!

Answer №3

Improved Solution

After further consideration, I have come up with an improved method to achieve the desired effect using CSS animations on a pseudo-element.

Here is the updated example:

div {
position: relative;
width: 190px;
height: 190px;
background-image:url('http://placekitten.com/190/190');
}

div::after {
content: '';
display: block;
position: absolute;
top: 0;
left: 0;
width: 190px;
height: 190px;
background-image:url('http://placekitten.com/190/190');
opacity: 0;
filter: grayscale(100%);
animation: waterfill 5s linear;
}

@keyframes waterfill {
0% {height: 190px; opacity: 1;}
20% {height: 190px; opacity: 1;}
100% {height: 0; opacity: 1;}
}
<div></div>


Original Approach:

In previous attempts, a CSS animation using @keyframes was suggested. However, this updated solution provides a more refined implementation.

img {
width: 190px;
height: 190px;
filter: grayscale(0%);
animation: colorImage 5s linear;
}


@keyframes colorImage {
0% {filter: grayscale(100%);}
80% {filter: grayscale(100%);}
100% {filter: grayscale(0%);}
}
<img src="http://placekitten.com/190/190" />

This updated animation also has a duration of 5 seconds, but offers a smoother transition from black and white to full color within the specified timeframe.

Answer №4

I trust this piece of code will be beneficial

<script type="text/JavaScript>
var picCount=0; // global
var picArray= ["Header1.png","Header1.jpg"] 
// Insert your original image names here
// gets next picture in array
function nextPic()
{ // check if adding 1 exceeds number of pics in array
picCount=(picCount+1<picArray.length)? picCount+1 : 0;
// create the img to display on page using the new pic reference
var build='<img border="0" src="'+picArray[picCount]+'" width="200" height="200">';
document.getElementById("imgHolder").innerHTML=build;
// repeat this after a pause of 2000ms (2sec).
setTimeout('nextPic()',2000)
}
</script>

Include this on your html page

<body onload="setTimeout('nextPic()',2000)">
<div id="imgHolder">
<img border="0" src="Header1.jpg" width="300" height="300">
</div>

Answer №5

It seems like my assumption was correct - the first image is simply a desaturated version of the second image, so there's no need to include both. Just stick with the colored one. To convert it to black and white, you can apply a grayscale filter:

img.blackwhite {
    filter: grayscale(100%);
}

Then make sure to add this class to your image:

<img id="myphoto" src="photo.jpg" class="blackwhite">

If you're looking for some sort of "animation," you can skip the classes and dynamically add the style using jQuery:

$("#myphoto").css("style","filter: grayscale("+(loadedBytes/totalBytes*100)+"%);");

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to adjust the anchor and h1 elements using CSS

I'm working on an HTML document with some markup, <a class="home-link" href="index.html" rel="home"> <h1 class="site-title">John Arellano's Personal Website</h1> </a> While styling the site title, I encountered a problem ...

Node.js has the ability to establish internal connections, however it cannot establish connections

I'm having an issue connecting to a JavaScript file on my local server. I'd like to input the external IP address and port in order for it to run externally. This functionality currently works when accessed locally. Below is the code from my serv ...

Adjust size of item within grid component in VueJS

I have a grid container with cells and a draggable item in a Vue project. I am trying to figure out how to resize the box inside the grid component (refer to images). https://i.stack.imgur.com/q4MKZ.png This is my current grid setup, and I would like the ...

What are some techniques for streamlining this code with Typescript?

I am currently working with the following code snippet: let doNavigate = this.currentScreen === removedFqn; if (doNavigate) { location.reload(); } Does anyone have any suggestions on how I can simplify this code using Typescript? ...

Japanese Character File Naming Convention

When dealing with certain Japanese characters, the content disposition header appears as follows: Content-Disposition: attachment; filename=CSV_____1-___.csv; filename*=UTF-8''CSV%E3%82%A8%E3%83%93%E3%83%87%E3%83%B3%E3%82%B91-%E3%82%B3%E3%83%94%E ...

What sets apart elem['textContent'] from elem.textContent?

When dealing with a HTMLElement in JavaScript, is there any distinction between the following lines of code: elem['textContent'] = "Test"; versus elem.textContent = "Test"; This question arises when setting the text content of an HTMLElement. ...

Tips for showcasing information entered into text fields within a single container within another container

After creating three divs, the first being a parent div and the next two being child divs placed side by side, I encountered an issue with displaying input values. Specifically, I wanted to take values from input text boxes within the second div (floatchil ...

Step-by-step guide on redirecting to a different page following a successful POST API call using Jquery

I have the code below in my JavaScript file. $scope.addLookupAction = function () { $("#importForm").attr("action", 'xyz.com'); success:function(response) { $log.info("Redirecting to lookup home page"); ...

How to retrieve the width of an unspecified element using JavaScript

Seeking help with a div element that adjusts its size based on the elements it contains. How can I determine the final size of this dynamic div without checking the sizes of its internal elements? I've attempted to parse all the properties of the obj ...

Rearrange and place items at the dropped location

I am looking to create a drag-and-drop feature for moving items from a list of products to an empty container. Upon completion, I need to save the location and the selected items in a database so that I can recall this layout later. However, I have encoun ...

How to troubleshoot Javascript code that fails to identify if a color is white

What could be causing my code to malfunction? I am attempting to determine if the paragraph text color is white (as determined by CSS settings). If it is indeed white, I want to change it to black for better visibility. function adjustColor() { if (d ...

The res.sendFile() function quickly delivers a 204 no content response

Currently, I am facing an issue with using Express' sendFile() function to send an image. The function does not seem to read my file at all and instead returns a 204 no-content response. Below is the code for my function/endpoint: @httpGet('/pri ...

What is the best way to compare two arrays in my JSON data?

Hello, I'm trying to compare two arrays - one from my JSON data and the second from a regular array. Specifically, I want to check if the ids of "cm:taggable" exist in my secondArray. JSON { "entry": { "isFile": true, "createdByUs ...

When the value in a required input field is empty, the border is activated and the color is styled

Can you please explain this to me? Try running this code in Firefox: http://jsfiddle.net/eMa8y/24/ Here is the HTML: <html> <head> <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> </head> ...

Use ajax, javascript, and php to insert information into a database

Issue at Hand: I am trying to extract the subject name from the admin and store it in the database. Following that, I aim to display the query result on the same webpage without refreshing it using Ajax. However, the current code is yielding incorrect outp ...

Position a modal in the vertical center with scroll functionality for handling extensive content

Looking for ways to tweak a Modal's CSS and HTML? Check out the code snippets below: div.backdrop { background-color: rgba(0, 0, 0, 0.4); height: 100%; left: 0; overflow: auto; position: fixed; top: 0; width: 100%; z-index: 2020; } ...

Ways to display one element while concealing it when another is clicked

I am utilizing a series of div elements that can be triggered with the following code snippet: $(".course_id").on("click", function(){ var id = $(this).data("id"); $("div#lessons_by_course_" + id).removeClass("hidden"); }); The ...

Trigger an event within a linked component

I've been working on a connected component where I'm attempting to dispatch the clear action from. Here's a snippet of the code: import {createElement} from 'react'; import reduce from 'lodash/fp/reduce'; import {connect ...

Continuously make Ajax requests to populate numerous div elements

There are two div elements present on my webpage. <div id="1"></div> <div id="2"></div> I am attempting to dynamically populate these divs using the following php call. <script> var queries = ["SELECT * from table1", "S ...