CSS Background Position: Animation and Performance

I saw many examples for animating the background position of elements to create nice looking scroll backgrounds.

These examples also tend to script in reset counters to put the starting position at the original location after a certain number of pixels.

My question is: is it possible to reset the background position for the lined background? This, of course, will lead to very large background positions over time, but if there is no significant difference in browser performance, it might be okay. I tested IE, Firefox and Chrome for an 8-hour period, and there seemed to be no negative consequences, although my mailboxes are relatively fast.

To answer the question "why not reset?" the question is, it just comes down to simplicity. I bring to life a lot of background elements, each of which has a different X / Y relationship, so I don’t have to figure out when it will be the perfect pixel choice to switch back to make my life easier.

Anyone have any thoughts on this?

+3
source share
2 answers

This, of course, will lead to very large values ​​of the background position over time.

Yes, this can be a problem if your code is similar to

el.style.backgroundPosition= '0 '+n+'px';

When n reaches a large number (usually 1,000,000,000,000,000,000,000), it toStringswitches to an exponential notation, which ultimately tries to establish:

el.style.backgroundPosition= '0 1e21px';

. , , , 1 < 31 . , - () 32 60 , .

, , .

modulo % , .

var framen1= 30;     // item 1 has 30 frames of animation
var framen2= 50;     // item 2 has 50 frames of animation
    ...
var framei1= (framei1+1)%framen1; // 0 to 29 then reset
var framei2= (framei2+1)%framen2; // 0 to 49 then reset

, , :

var frametime1= 100; // item 1 updates 10 times a second
var frametime2= 40;  // item 2 updates 25 times a second
    ...

var dt= new Date()-t0; // get time since started animation

var framei1= Math.floor(dt/frametime1) % framen1;
var framei2= Math.floor(dt/framelength2) % numberofframes2;

document.getElementById('div1').style.backgroundPosition= '0 '+(framei1*24)+'px';
document.getElementById('div2').style.backgroundPosition= '0 '+(framei2*24)+'px';
   ...
+4

, - , 8- , , . .

+1

Source: https://habr.com/ru/post/1723504/


All Articles