Pro CSS3 Animation

(Tuis.) #1

ChApter 8 ■ IntegrAtIng CSS3 AnImAtIon wIth reSponSIve weB DeSIgn AnD JAvASCrIpt


In an effort to reduce the amount of hand-coding you have to do in any page, you will use JavaScript to solve
both of these issues. To keep things simple, you use red div elements as the animated objects. At the bottom of a
page you’ll add the script shown in Listing 8-19.


Listing 8-19. JavaScript Code to Create Random Scattered Elements



You use a JavaScript loop to create as many copies of the div element as you wish. For each element, you’ll
use three variables to determine its horizontal position, offset from the top edge of the viewport, together with the
horizontal and vertical size.
However many elements you have will all follow the same keyframe animation rules shown in Listing 8-20.


Listing 8-20. JavaScript Code to Create Random Scattered Elements


html { height: 100%; }
body { min-height: 100%; margin: 0; }
@keyframes snowflake {
100% { transform: translateY(1800px) rotate(1200deg); }
}
div { background: red; position: absolute; animation: snowflake 40s linear infinite; }


Although this works, there are several issues: all of the shapes fall at the same rate, and turn synchronously.
An element that is small appears to be further away, and should fall more slowly, while all elements should
start at a randomized rotation. In order to achieve this, you’ll create several classes that will call the keyframe
animation with different timings and apply the classes with JavaScript, based on the element’s size (Listing 8-21).


Listing 8-21. CSS and JavaScript Code to Create Randomized Scattered Elements


Free download pdf