Home > Blockchain >  CSS linear gradient background changes over time
CSS linear gradient background changes over time

Time:07-30

I would like to create a div with a gradient background (2 colors from top to bottom) that changes colors over time.

For example: the div has a red (top) and blue (bottom) linear gradient background and I want it to gradually turn yellow (top) and purple (bottom) after ten minutes.

Important: the background must not change suddenly when 10 minutes have elapsed but must change little by little for the entire duration of 10 minutes.

My needs: what I should do is change the background to recreate the colors of the sky in the most realistic way possible. So having available the times of sunset, sunrise, day, and night and their respective durations, I wanted to change the color of the background recreating the sky in those moments of the day. The result would be animations of the same duration of day, night, sunset and sunrise that change the background color with gradients. Dynamically changing the duration of the animation and checking what time of day I am in order to start the correct animation of the background colors I am able to do it but I don't know how to animate the linear gradient over time.

How can I do that? Thanks in advance.

CodePudding user response:

I hope this is what you wanted:

var intervalID;
var seconds=20;//Here u set time
var updateTimeMs = 10;
var noSteps=seconds*1000/updateTimeMs;

intervalID = setInterval(myTimer, updateTimeMs);
var counter=0;

function myTimer() {
  counter  ;
  if (counter == noSteps)
     clearInterval(intervalID);
    
    var prcStep = Math.trunc(counter/noSteps*100);        
    var newValDown =  Math.trunc(255-(255/100)*prcStep);
    var newValUp =  Math.trunc((255/100)*prcStep);
        
    
  document.getElementById("myDiv").style.backgroundColor = `rgba(255,${newValUp},0,1)`;
  document.getElementById("myDiv").style.backgroundImage =`linear-gradient(to bottom, rgba(0,0,0,0) 0%,rgba(0,0,0,0.01) 1%,rgba(${newValUp},0,255,1) 100%)`;
  }
.grad {
  background-color : rgba(255,0,0,1);
  background-image:linear-gradient(to bottom, rgba(0,0,0,0) 0%,rgba(0,0,0,0.01) 1%,rgba(0,0,255,1) 100%);
}
<div id="myDiv"  style="width:600px;height:200px;border:solid 1px black">

</div>

CodePudding user response:

What you could do is create a gradient containing all of your colors red top & blue bottom on the left & yellow top & purple bottom, and you would animate that by moving it around slowly. In that case i don't think background: linear-gradient does animate so maybe refer to that method

.grad {
    background-color : rgba(255,0,0,1);
    background-image: linear-gradient(to bottom, rgba(0,0,0,0) 0%, rgba(0,0,0,0.01) 1%, rgba(0,0,255,1) 100%);
    animation: gradient 3600s ease linear;
}
@keyframes gradient {
    0% {
        background-position: left;
    }
    100% {
        background-position: right;
    }
  • Related