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

What is the best way to test chained function calls using sinon?

Here is the code I am currently testing: obj.getTimeSent().getTime(); In this snippet, obj.getTimeSent() returns a Date object, followed by calling the getTime() method on that Date. My attempt to stub this functionality looked like this: const timeStu ...

Hide the button with jQuery Ajax if the variable is deemed acceptable upon submission

I need to figure out how to hide the submit button if the email entered is the same as the one in the database from action.php. Can anyone help me with integrating this functionality into my existing code? <form onsubmit="return submitdata();"> ...

Organizing subcategories within a dropdown checklist

I am currently working on a list that utilizes dropdownchecklist and I am looking to create subgroups from the elements in the list. The goal is that by clicking on a subgroup checkbox, it will automatically check all elements associated with it. Below is ...

Transform the JSON object into a TypeScript array

Currently working on a project that requires converting a JSON object into a TypeScript array. The structure of the JSON is as follows: { "uiMessages" : { "ui.downtime.search.title" : "Search Message", "ui.user.editroles.sodviolation.entries" : ...

Utilizing JavaScript for Formatting and Comparing Dates

Here, I would like to compare the current date with a user-inputted date. <script type="text/javascript"> $(document).ready(function(){ $("#date").change(function(){ var realDate = new Date(); var startDate = new ...

Is it really necessary to still think poorly of JavaScript in 2011?

Here's an intriguing question for you. I've tested out a variety of popular websites, including Facebook, and I've noticed that many features still work perfectly fine even when JavaScript is disabled. People always used to say that JavaScr ...

How can I validate HTML input elements within a DIV (a visible wizard step) situated within a FORM?

I recently made a decision to develop a wizard form using HTML 5 (specifically ASP.NET MVC). Below is the structure of my HTML form: @using (Html.BeginForm()) { <div class="wizard-step"> <input type="text" name="firstname" placeholder ...

Is it better to verify the data from an ajax request or allow JavaScript to generate an error if the data is empty

Is it better to check if the necessary data is present when handling success data in jQuery, like this? success: function (data) { if (data.new_rank !== undefined) { $('._user_rank').html(data.new_rank); } } Or should you just l ...

JavaScript Promise Synchronization

I have a JavaScript function that returns an object using promises. The first time the function is called, it fetches the object, but for subsequent calls, it returns a cached instance. To simulate the fetching process, I've added a delay. var Promis ...

Having trouble getting the toggleClass function to work properly?

I'm facing an issue with some straightforward code that I've written. $(function() { $("#tren").click(function() { $("#trens").toggleClass("show"); }); }); .show { color: "red"; } <ul> <li id="tren">Some text</li> < ...

Creating an App on Shopify

After working on Shopify development for a little bit, I have encountered a specific requirement from my client that is not currently available in the app store. The task involves: Creating two discount tiers based on the total value of the cart (e.g. 1 ...

Updating a table dynamically after a form submission using jQuery, Ajax, and PHP without needing to refresh the page

My current setup involves an ajax form along with a table. Here is the ajax code I am using: $(function () { $(".submitann").click(function () { var title = $("#title").val(); var announcement = $("#announcement").val(); var d ...

Passing information from a directive to a controller using AngularJS

I am looking to display the progress of a file upload using a file reader. Here is the HTML code snippet I have: <md-progress-linear id="file-progress-indicator" md-mode="determinate" value="{{progress}}"></md-progress-linear> and below is m ...

In the Redux framework, the reducer fails to identify the action object

I'm currently working on a React project using Redux. I've encountered an issue where my reducer is not recognizing the action type being sent to it, or even the action itself. The error message I am receiving is TypeError: Cannot read property & ...

The issue with the jQuery click event arises when utilizing the "Module Pattern"

Exploring the Module Pattern as described by Chris Coyyer here, I, an intermediate front-end JS developer, have encountered a problem. Specifically, when attempting to utilize a jQuery selector stored in the settings object, I am unable to trigger a click ...

Show one line of text at a time with a pause in between each one

On my HTML page, I am looking to showcase text lines in succession with a delay. The unique condition is that when the second line appears, the color of the first line should change. Then, as the third line emerges, the color of the second line should also ...

Issue with loading dynamic content on a webpage using HTML and JavaScript through AJAX

I am currently using the jQuery UI Tabs plugin to dynamically load HTML pages through AJAX. Here is the structure of the HTML code: <div id="tabs"> <ul> <li><a href="pageWithGallery.html" title="pageWithGallery">Gallery< ...

Tips for creating a typescript typeguard function for function types

export const isFunction = (obj: unknown): obj is Function => obj instanceof Function; export const isString = (obj: unknown): obj is string => Object.prototype.toString.call(obj) === "[object String]"; I need to create an isFunction method ...

webdriverIO encountered an unhandled promise rejection, resulting in a NoSuchSessionError with the message "invalid session id

I am currently learning how to conduct UI testing using Jasmine and WebdriverIO in conjunction with NodeJS. Below is a snippet of my test code: const projectsPage = require('../../lib/pages/projects.page'); const by = require('selenium-we ...

Does TypeGraphQl have the capability to automatically format SQL queries?

I am utilizing TypeORM in conjunction with TypeGraphQL. I am curious about the SQL query result that TypeGraphQL provides. For instance, if I have a User Table with numerous columns and a simple resolver like this: @Resolver() class UserResolver { @Q ...