css linear-gradient background CPU high usage - css

Need to create linear gradient animation in body but it uses cpu a lot which causes fans to run loudly.
I found this solution
animated linear gradient devouring CPU usage
this trick lowers cpu usage down to 3-5% which is great. But when you resize the window it create a bug in the background.
Tried to create resize function because I guess when you resize the window the width property changes which causes the bug. But it didn't work out.
[Codepen](https://codepen.io/iclassici/pen/poPXRyp)

In doing:
body.classList.remove('bg');
body.classList.add('bg');
actually nothing happens because the class is restored before the system has had a chance to recalculate/redraw stuff.
You'll need to remove the class as you have done, and then wait before reinstating it. Try setTimeout or requestAnimationFrame.
If you could make you code into a snippet which we can run in your question that would help us test things and give a fuller answer.
UPDATE: taking the code given in the codepen, this snippet makes a change to the resize function, removing a bganimation class, setting a short timeout and reinstating the class. This ensures that the system will reset whatever parameters it is giving the GPU.
Note: on my reasonably powerful laptop, Windows 10, the animation of the background is taking less than 2% CPU mostly and around 20% of the GPU.
window.addEventListener("resize", myFunction);
function myFunction() {
body = document.getElementsByTagName('body')[0];
body.classList.remove('bganimation');
setTimeout(function() {
body.classList.add('bganimation');
}, 100);
}
.bg {
width: 100vw;
height: 100vh;
}
.bg::before {
content: '';
position: fixed;
z-index: -2;
top: 0;
left: 0;
width: 600%;
height: 100%;
bottom: 0;
background: linear-gradient(45deg, #F17C58, #E94584, #24AADB, #27DBB1, #FFDC18, #FF3706);
background-size: 100% 100vh;
background-repeat: no-repeat no-repeat;
background-position: left top;
}
.bganimation {
animation: gradient 16s linear infinite alternate;
}
#keyframes gradient {
0% {
transform: translateX(0);
}
100% {
transform: translateX(-400vw);
/* 5/6x100% */
}
}
<body class="bg bganimation">
</body>

Related

CSS Animation ( #keyframes ) is heating up CPU

I have a simple CSS animation as you can see here: http://jsfiddle.net/628uzdfn/
It simply has one animation #keyframes which is causing the problem ( when I remove animation, it doesn't heat up CPU )( stylus syntax ):
#keyframes moving
from
transform translateX( 0 ) translateZ( 0 )
to
transform translateX( -15% ) translateZ( 0 )
The problem is if you let this page live for more than 10 seconds, you're going to feel the warmth under your laptop. If you leave it for more than 30 seconds, it will sound like a tractor!
I've already read performance-related stuff on html5rocks so I tried to limit my animating properties to only transform even tried to put translateZ( 0 ) to ask for help from GPU, but it just doesn't change a thing.
You can see my performance profiling here as well:
Is there anything I'm doing wrong?
What should I do to improve my animation in terms of its performance?
Update: Forgot to mention this animation is infinite so it can be the problem, but why is it happening? I've already seen many infinite CSS-animations which didn't make a performance issue. It should be something else causing the problem.
Not sure what wrong with your computer but in my computer, CPU is not a big problem. Testing in Chrome 66.0, Ubuntu 18.04. Your animation is simple but it can be optimized 2x (CPU) better just by changing translateX( -15% ) to translateX( -108px ). 108px equal 15% width of your element but it is in fixed pixcel. Browser do not need to re-caculate the value each frame of animation. So it will definitely use less CPU. Here is the result of my CPU before and after optimizing
Before
After
There's no way for me to test this, but I'm giving it a shot.
My initial thoughts on why this might be happening after you've already made the correct css GPU enhancements is from the %'s and float's and the amount of .block's your animating (just some wild guesses).
I made the changes and recreated the .block's with a repeating-linear-gradient with a few other changes.
https://codepen.io/oneezy/pen/JwbpPz
#keyframes moving {
from { transform: translateX(-50px) translateZ(0); }
to { transform: translateX(-150px) translateZ(0); }
}
.container {
width: 600px;
height: 100px;
}
.street {
background: #333;
height: 100%;
width: 100%;
display: flex; flex-direction: column; justify-content: center;
overflow: hidden;
}
.block {
animation: moving 1.5s linear infinite;
will-change: transform;
display: block;
width: 200%; height: 6px;
transform: translateX(-50px);
background-image: repeating-linear-gradient(to right, transparent, transparent 50px, white 50px, white 100px);
}
<div class="container">
<div class="street">
<div class="block"></div>
</div>
</div>

CSS3 animation transform jumping at osx Chrome

I am having an issue with Chrome (v. 67) at OSX and movement animations. I've prepared JS fiddle with it:
https://jsfiddle.net/5m173ghv/31/
If you open it at safari it is working very good. But, when you will use chrome it has little lags when moving.
I cannot describe it a bit more... You need to open it and try yourself on the big screen... Please look carefully at white box. You will see that this box has sometimes something like lags or small jumps(?)...
This is very weird. I've tried almost every answer from the internet (trust me ;) ).
I also tried:
Change transforms at animation into position (left)
Change animations into transitions
adding additional parameters (backface-visibility, perspective, will-change...)
Changing sequences of animation to have more steps (per 10%)
Debugging on chrome dev tools (~30-40fps)
Adding transforms like translateZ(0)
You think that this is chrome bug or maybe my fault? Do you have any solution for that?
Here you have code:
HTML
<span class="spark"></div>
SCSS
body {
background-color: black;
}
#keyframes left-to-right {
0% {
transform: translate3d(0,0,0);
}
100% {
transform: translate3d(50vw,0,0);
}
}
.spark {
position: absolute;
top: 30px;
width: 322px;
height: 500px;
background-color: white;
transform: translate3d(0,0,0);
backface-visibility: hidden;
perspective: 1000px;
animation: left-to-right 5s infinite linear;
will-change: transform;
pointer-events: none;
user-select: none;
}

Start Non-looping GIF from beginning with CSS only

I'd like to know if it's possible to start a non-looping GIF from the beginning with CSS animation? For my example I have two GIFs. The first counts 1,2,3 each second - the second GIF counts 4,5,6 each second.
My goal is to show the first GIF until it counts to 3, then switch to the second GIF until it counts to 6, where it stops. My issue is that the second GIF will always be on 6 if I get it to show, at all.
My setup is as follows:
<div id="gif-two" class="gif"></div>
<div id="gif-one" class="gif"></div>
CSS
.gif {
width: 300px;
height: 300px;
position: absolute;
top: 0;
left: 50%;
margin-left: -150px;
}
#gif-one {
background: url("http://i.imgur.com/jLTVHdY.gif");
}
#gif-two {
background: url("http://i.imgur.com/O61k5Nf.gif");
}
I'm at a loss on how to handle this at the moment. I've tried toggling visibility - but have no idea how to make this work in just CSS.
Note: It is possible to achieve what you want by using CSS animations (as you will see from this answer) but I'd recommend you to combine them into the same GIF and use it that way because the approach used in this answer is too complex (so much so that I may struggle to explain it).
When the GIF is added as abackground-image, both images are loaded at pretty much same time by the browser and the GIF animation starts executing immediately. This means that change from 4-5 on the second GIF is happening at almost the same time as 1-2 on the first GIF. So, when the first GIF's loop ends, the second GIF's loop would also have ended and this is why you'd always see only 6.
The only way to avoid that from happening is to make the browser load the image after the first loop is completed. Below snippet achieves just this in a very complicated manner. The below is how:
Initially the background image is added only to the first div (because it needs to start its own loop immediately).
An animation with duration of 3s is set to the first div. This animation will hide the first div (and its background image) after around 3s, which is, the time take for its loop to complete. The opacity change from 1 to 0 starts at 95% itself to create a fade-out effect. Otherwise, at the end of loop it looks as though it blinks off and the second GIF blinks on (which doesn't look pleasing).
The second div doesn't have any background image added to it at the start because if it is added then it will load immediately and start its loop. An animation with 3s duration is added to this also.
The animation on the second div is such that it gets the background image added to it only at the end of the animation (100%). This means that the second image is loaded only after 3s (duration) and it starts its loop only from that time (by which, the loop of the first is already completed).
.gif {
width: 300px;
height: 300px;
position: absolute;
top: 0;
left: 50%;
margin-left: -150px;
}
#gif-one {
animation: img 3s linear forwards;
background: url(http://i.imgur.com/jLTVHdY.gif?3);
}
#gif-two {
animation: img2 3s linear forwards;
z-index: -1;
}
#keyframes img {
0%, 95% {
opacity: 1;
}
100% {
opacity: 0;
}
}
#keyframes img2 {
0%, 99% {
background-image: none;
}
100%{
background: url(http://i.imgur.com/O61k5Nf.gif?3);
}
}
<div id="gif-one" class="gif"></div>
<div id="gif-two" class="gif"></div>
Note: As I was writing this answer, I realized that setting the background-image within #keyframes rules does not work in IE and Firefox. Hence, the above solution is WebKit only. Also, as far as I am aware there is no other pure CSS solution possible. You would have to use JavaScript and that would help in the cache busting that CBroe is referring to also. Below is a sample demo using JS.
Using single element + JS:
window.onload = function() {
var el = document.querySelector('.gif');
el.style.backgroundImage = 'url(http://i.imgur.com/jLTVHdY.gif' + Math.random() + ')';
setTimeout(function() {
el.style.backgroundImage = 'url(http://i.imgur.com/O61k5Nf.gif' + Math.random() + ')';
}, 3250);
}
.gif {
width: 300px;
height: 300px;
position: absolute;
top: 0;
left: 50%;
margin-left: -150px;
}
<div class="gif"></div>
Using two elements + JS:
window.onload = function() {
var el1 = document.querySelector('#gif-one'),
el2 = document.querySelector('#gif-two');
el1.style.backgroundImage = 'url(http://i.imgur.com/jLTVHdY.gif' + Math.random() + ')';
setTimeout(function() {
el1.style.opacity = '0';
el2.style.backgroundImage = 'url(http://i.imgur.com/O61k5Nf.gif' + Math.random() + ')';
}, 3250);
}
.gif {
width: 300px;
height: 300px;
position: absolute;
top: 0;
left: 50%;
margin-left: -150px;
transition: opacity .05s .5s;
}
<div id="gif-one" class="gif"></div>
<div id="gif-two" class="gif"></div>

CSS: Animation vs. Transition

So, I understand how to perform both CSS3 transitions and animations. What is not clear, and I've googled, is when to use which.
For example, if I want to make a ball bounce, it is clear that animation is the way to go. I could provide keyframes and the browser would do the intermediates frames and I'll have a nice animation going.
However, there are cases when a said effect can be achieved either way. A simple and common example would be implement the facebook style sliding drawer menu:
This effect can be achieved through transitions like so:
.sf-page {
-webkit-transition: -webkit-transform .2s ease-out;
}
.sf-page.out {
-webkit-transform: translateX(240px);
}
http://jsfiddle.net/NwEGz/
Or, through animations like so:
.sf-page {
-webkit-animation-duration: .4s;
-webkit-transition-timing-function: ease-out;
}
.sf-page.in {
-webkit-animation-name: sf-slidein;
-webkit-transform: translate3d(0, 0, 0);
}
.sf-page.out {
-webkit-animation-name: sf-slideout;
-webkit-transform: translateX(240px);
}
#-webkit-keyframes sf-slideout {
from { -webkit-transform: translate3d(0, 0, 0); }
to { -webkit-transform: translate3d(240px, 0, 0); }
}
#-webkit-keyframes sf-slidein {
from { -webkit-transform: translate3d(240px, 0, 0); }
to { -webkit-transform: translate3d(0, 0, 0); }
}
http://jsfiddle.net/4Z5Mr/
With HTML that looks like so:
<div class="sf-container">
<div class="sf-page in" id="content-container">
<button type="button">Click Me</button>
</div>
<div class="sf-drawer">
</div>
</div>
And, this accompanying jQuery script:
$("#content-container").click(function(){
$("#content-container").toggleClass("out");
// below is only required for css animation route
$("#content-container").toggleClass("in");
});
What I'd like to understand is what are the pros and cons of these approaches.
One obvious difference is that animating is taking a whole lot more code.
Animation gives better flexibility. I can have different animation for sliding out and in
Is there something that can be said about performance. Do both take advantage of h/w acceleration?
Which is more modern and the way going forward
Anything else you could add?
It looks like you've got a handle on how to do them, just not when to do them.
A transition is an animation, just one that is performed between two distinct states - i.e. a start state and an end state. Like a drawer menu, the start state could be open and the end state could be closed, or vice versa.
If you want to perform something that does not specifically involve a start state and an end state, or you need more fine-grained control over the keyframes in a transition, then you've got to use an animation.
I'll let the definitions speak for themselves (according to Merriam-Webster):
Transition: A movement, development, or evolution from one form, stage, or style to another
Animation: Endowed with life or the qualities of life; full of movement
The names appropriately fit their purposes in CSS
So, the example you gave should use transitions because it is only a change from one state to another
A shorter answer, straight on point:
Transition:
Needs a triggering element (:hover, :focus etc.)
Only 2 animation states (start and end)
Used for simpler animations (buttons, dropdown menus and so on)
Easier to create but not so many animation/effect possibilities
Animation #keyframes:
It can be used for endless animations
Can set more than 2 states
No boundaries
Both use CPU acceleration for a much smoother effect.
Animation takes a lot more code unless you're using the same transition over and over, in which case an animation would be better.
You can have different effects for sliding in and out without an animation. Just have a different transition on both the original rule and the modified rule:
.two-transitions {
transition: all 50ms linear;
}
.two-transitions:hover {
transition: all 800ms ease-out;
}
Animations are just abstractions of transitions, so if the transition is hardware accelerated, the animation will be. It makes no difference.
Both are very modern.
My rule of thumb is if I use the same transition three times, it should probably be an animation. This is easier to maintain and alter in the future. But if you are only using it once, it is more typing to make the animation and maybe not worth it.
Animations are just that - a smooth behavior of set of properties. In other words it specifies what should happen to a set of element's properties. You define an animation and describe how this set of properties should behave during the animation process.
Transitions on the other side specify how a property (or properties) should perform their change. Each change. Setting a new value for certain property, be it with JavaScript or CSS, is always a transition, but by default it is not smooth. By setting transition in the css style you define different (smooth) way to perform these changes.
It can be said that transitions define a default animation that should be performed every time the specified property has changed.
Is there something that can be said about performance. Do both take
advantage of h/w acceleration?
In modern browsers, h/w acceleration occurs for the properties filter, opacity and transform. This is for both CSS Animations and CSS Transitions.
.yourClass {
transition: all 0.5s;
color: #00f;
margin: 50px;
font-size: 20px;
cursor: pointer;
}
.yourClass:hover {
color: #f00;
}
<p class="yourClass"> Hover me </p>
CSS3 Transitions brought frontend developers a significant ability to modify the appearance and behavior of an element as relative to a change in his state. CSS3 animations extends this ability and allow to modify the appearance and behavior of an element in multiple keyframes, so transitions provides us the ability to change from one state to another, while that animations can set multiple points of transition within different keyframes.
So, let's look at this transition sample where applied a transition with 2 points, start point at left: 0 and an end point at left: 500px
.container {
background: gainsboro;
border-radius: 6px;
height: 300px;
position: relative;
}
.ball {
transition: left 2s linear;
background: green;
border-radius: 50%;
height: 50px;
position: absolute;
width: 50px;
left: 0px;
}
.container:hover .ball{
left: 500px;
}
<div class="container">
<figure class="ball"></figure>
</div>
The above can be also created via animation like so:
#keyframes slide {
0% {
left: 0;
}
100% {
left: 500px;
}
}
.container {
background: gainsboro;
border-radius: 6px;
height: 200px;
position: relative;
}
.ball {
background: green;
border-radius: 50%;
height: 50px;
position: absolute;
width: 50px;
}
.container:hover .ball {
animation: slide 2s linear;
}
<div class="container">
<figure class="ball"></figure>
</div>
And if we would like another in-between point, it would be possible to achieve only via animation, we can add another keyFrame to achieve this and this is the real power of animation over transition:
#keyframes slide {
0% {
left: 0;
}
50% {
left: 250px;
top: 100px;
}
100% {
left: 500px;
}
}
.container {
background: gainsboro;
border-radius: 6px;
height: 200px;
position: relative;
}
.ball {
background: green;
border-radius: 50%;
height: 50px;
position: absolute;
width: 50px;
}
.container:hover .ball {
animation: slide 2s linear;
}
<div class="container">
<figure class="ball"></figure>
</div>
transition can go reverse from middle of the way, but animation replay the keyframes from start to end.
const transContainer = document.querySelector(".trans");
transContainer.onclick = () => {
transContainer.classList.toggle("trans-active");
}
const animContainer = document.querySelector(".anim");
animContainer.onclick = () => {
if(animContainer.classList.contains("anim-open")){
animContainer.classList.remove("anim-open");
animContainer.classList.add("anim-close");
}else{
animContainer.classList.remove("anim-close");
animContainer.classList.add("anim-open");
}
}
*{
font: 16px sans-serif;
}
p{
width: 100%;
background-color: #ff0;
}
.sq{
width: 80px;
height: 80px;
margin: 10px;
background-color: #f00;
display: flex;
justify-content: center;
align-items: center;
}
.trans{
transition: width 3s;
}
.trans-active{
width: 200px;
}
.anim-close{
animation: closingAnimation 3s forwards;
}
.anim-open{
animation: openingAnimation 3s forwards;
}
#keyframes openingAnimation {
from{width: 80px}
to{width: 200px}
}
#keyframes closingAnimation {
from{width: 200px}
to{width: 80px}
}
<p>Try click them before reaching end of movement:</p>
<div class="sq trans">Transition</div>
<div class="sq anim">Animation</div>
in addition, if you want the javascript to listen for end of transition, you'll get one event for each property that you change.
for example transition: width 0.5s, height 0.5s. the transitionend event will trigger two times, one for width and one for height.
Just a summary, thanks to this post, there are 5 main differences between CSS transitions vs CSS animations:
1/ CSS transitions:
Animate an object from one state to another, implicitly by browser
Cannot loop
Need a trigger to run (:hover, :focus)
Simple, less code, limited powerful
Easy to work in JavaScript
2/ CSS animations:
Freely switch between multiple states, with various properties and time frame
Can loop
Don’t need any kind of external trigger
More complex, more code, more flexible
Hard to work in JavaScript due to syntax for manipulating keyframes
I believe CSS3 animation vs CSS3 transition will give you the answer you want.
Basically below are some takeaways :
If performance is a concern, then choose CSS3 transition.
If state is to be maintained after each transition, then choose CSS3 transition.
If the animation needs to be repeated, choose CSS3 animation. Because it supports animation-iteration-count.
If a complicated animation is desired. Then CSS3 animation is preferred.
Don't bother yourself which is better. My give away is that, if you can solve your problem with just one or two lines of code then just do it rather than writing bunch of codes that will result to similar behavior.
Anyway, transition is like a subset of animation. It simply means transition can solve certain problems while animation on the other hand can solve all problems.
Animation enables you to have control of each stage starting from 0% all the way to 100% which is something transition cannot really do.
Animation require you writing bunch of codes while transition uses one or two lines of code to perform the same result depending on what you are working on.
Coming from the point of JavaScript, it is best to use transition. Anything that involve just two phase i.e. start and finish use transition.
Summary, if it is stressful don't use it since both can produce similar result

Best practice/tool for AJAX loading indicator as animated PNG sprite?

Obviously GIFs do not support an alpha channel. If I waned an alpha-channel capable “throbber,” “spinner,” or Ajax loading indicator, it seems the only (post-IE6) cross-browser option would be a sprited PNG containing all the states of the throbber.
I guess I would be animating it myself using JavaScript to advance the frames (using requestAnimationFrame when available) by changing a class or something that sets the background origin.
I can't seem to find anything that helps generate this, specifically. Does anyone know of any? Any best practices I should know about? (I know that e.g. Compass has a sprite helper I can take advantage of for automating the CSS portion, at least.)
I don't think there are any "best practices", but there are a lot of tools out there. Start by doing a search for "animated gif to sprite". If you have ImageMagick installed take a look at this post:
http://forums.tigsource.com/index.php?topic=9041.msg282280#msg282280
Once you have a sprite the options for animation all depend on how you prefer to code your javascript.
What is your browser matrix? If you have the luxury (FF, Safari, Chrome, etc.) you can use CSS animation like the following which assumes each frame is 100px square and you sprite has 5 frames.
#animatedImage {
width: 100px;
height: 100px;
background: transparent url(sprite.png) no-repeat 0 0;
animation-duration: 400ms;
animation-iteration-count: infinite;
animation-timing-function: step-start;
animation-name: animateSprite;
}
#-webkit-keyframes animateSprite {
0% { background-position: 0 0; }
20% { background-position: -400px 0; }
40% { background-position: -300px 0; }
60% { background-position: -200px 0; }
80% { background-position: -100px 0; }
100% { background-position: 0 0; }
}

Resources