Summary of HTML5 animation effects,
Let's take a sports car as an example to illustrate three HTML5 animation methods with clear ideas. animations are not just canvas, but also css3 and javascript. achieve optimal implementation through reasonable selection.
PS: Due to the video card, recording frame interval, and possible reasons for your computer processor, the playing process may be a bit less smooth or distorted!
There are three implementation methods:
(1) combine canvas elements with JS
(2) Pure CSS3 animation (not supported by all mainstream browsers, such as IE)
(3) CSS3 combined with Jquery
Knowing how to use CSS3 animation is more important than knowing how to use <canvas> elements: because browsers can optimize the performance of those elements (usually their styles, such as CSS ), however, the effects of canvas custom images cannot be optimized. The reason is that the hardware used by the browser depends mainly on the video card capability. Currently, the browser does not give us the right to directly access the video card. For example, every painting operation has to call some functions in the browser.
1. canvas
Html code:
The Code is as follows:
<Html>
<Head>
<Meta charset = "UTF-8"/>
<Title> Animation in HTML5 using the canvas element </title>
</Head>
<Body onload = "init ();">
<Canvas id = "canvas" width = "1000" height = "600"> Your browser does not support the <code> <canvas> </code>-element. please think about updating your brower! </Canvas>
<Div id = "controls">
<Button type = "button" onclick = "speed (-0.1);"> Slower </button>
<Button type = "button" onclick = "play (this);"> Play </button>
<Button type = "button" onclick = "speed (+ 0.1)"> Faster </button>
</Div>
</Body>
</Html>
Js Code:
Define some variables:
The Code is as follows:
Var dx = 5, // Current Rate
Rate = 1, // current playback speed
Ani, // current animation Loop
C, // Canvas Context)
W, // car [hidden] (Canvas Context)
GrassHeight = 130, // background height
CarAlpha = 0, // tire rotation angle
CarX =-400, // The Position of the car on the X axis (will be changed)
CarY = 300, // The Position of the car on the Y axis (will be constant)
CarWidth = 400, // car width
CarHeight = 130, // car height
TiresDelta = 15, // distance from a tire to the nearest car chassis
AxisDelta = 20, // distance between the axle and the tire of the chassis at the bottom of the car
Radius = 60; // tire radius
To instantiate the car canvas (hidden at first), we use the following self-executed anonymous Function
The Code is as follows:
(Function (){
Var car = document. createElement ('canvas '); // create an element
Car. height = carHeight + axisDelta + radius; // set the height.
Car. width = carWidth; // set the width.
W = car. getContext ('2d ');
})();
Click the "Play" button and repeat the "draw a car" operation on a regular basis to simulate the "frame playback" function:
The Code is as follows:
Function play (s) {// parameter s is a button
If (ani) {// if ani is not null, it indicates that we already have an animation.
ClearInterval (ani); // so we need to clear it (stop animation)
Ani = null;
S. innerHTML = 'play'; // rename this button to "Play"
} Else {
Ani = setInterval (drawCanvas, 40); // we will set the animation to 25fps [frame per second], 40/1000, that is, 1/25
S. innerHTML = 'pause'; // rename the button to "Suspend"
}
}
Acceleration and deceleration are achieved by changing the moving distance in the following ways:
The Code is as follows:
Function speed (delta ){
Var newRate = Math. max (rate + delta, 0.1 );
Dx = newRate/rate * dx;
Rate = newRate;
}
Page loading initialization method:
// Init
Function init (){
C = document. getElementById ('canvas '). getContext ('2d ');
DrawCanvas ();
}
Main debugging method:
The Code is as follows:
Function drawCanvas (){
C. clearRect (, c. canvas. width, c. canvas. height); // clear the Canvas (displayed) to avoid errors.
C. save (); // save the current coordinate value and status. The corresponding operation is similar to "push ".
DrawGrass (); // draws the background
C. translate (carX, 0); // move the start Coordinate
DrawCar (); // draw a car (hidden canvas)
C. drawImage (w. canvas, 0, carY); // draw the final displayed car
C. restore (); // restore the Canvas status, which corresponds to a pop-like operation.
CarX + = dx; // reset the position of the car on the X axis to simulate forward
CarAlpha + = dx/radius; // increase the tire angle proportionally
If (carX> c. canvas. width) {// you can specify some regular boundary conditions.
CarX =-carWidth-10; // You can also reverse the speed to dx * =-1;
}
}
Background:
The Code is as follows:
Function drawGrass (){
// Create a linear gradient. The first two parameters are the start point coordinate of the gradient, and the last two parameters are the coordinates of the end point of the gradient.
Var grad = c. createLinearGradient (0, c. canvas. height-grassHeight, 0, c. canvas. height );
// Specify gradient for a linear gradient. 0 indicates the starting color of the gradient, and 1 indicates the ending color of the gradient.
Grad. addColorStop (0, '#33cc00 ');
Grad. addColorStop (1, '#66FF22 ');
C. fillStyle = grad;
C. lineWidth = 0;
C. fillRect (0, c. canvas. height-grassHeight, c. canvas. width, grassHeight );
}
Body painting:
The Code is as follows:
Function drawCar (){
W. clearRect (0, 0, w. canvas. width, w. canvas. height); // clear the hidden canvas
W. strokeStyle = '# FF6600'; // you can specify the border color.
W. lineWidth = 2; // you can specify the Border Width in pixels.
W. fillStyle = '# FF9900'; // you can specify the fill color.
W. beginPath (); // start to draw a new path.
W. rect (0, 0, carWidth, carHeight); // draw a rectangle
W. stroke (); // draw a border
W. fill (); // fill the background
W. closePath (); // close the new path.
DrawTire (tiresDelta + radius, carHeight + axisDelta); // we start to draw the first wheel.
DrawTire (carWidth-tiresDelta-radius, carHeight + axisDelta); // same, second
}
Paint tires:
The Code is as follows:
Function drawTire (x, y ){
W. save ();
W. translate (x, y );
W. rotate (carAlpha );
W. strokeStyle = '# 3300FF ';
W. lineWidth = 1;
W. fillStyle = '# 0099FF ';
W. beginPath ();
W. arc (, radius, * Math. PI, false );
W. fill ();
W. closePath ();
W. beginPath ();
W. moveTo (radius, 0 );
W. lineTo (-radius, 0 );
W. stroke ();
W. closePath ();
W. beginPath ();
W. moveTo (0, radius );
W. lineTo (0,-radius );
W. stroke ();
W. closePath ();
W. restore ();
}
Since the principle is simple and the code is annotated in detail, I will not explain it here!
2. CSS3
You will see that we have completely achieved the same animation effect as above without passing a javascript code:
HTML code:
The Code is as follows:
<Html>
<Head>
<Meta charset = "UTF-8"/>
<Title> Animations in HTML5 using CSS3 animations </title>
</Head>
<Body>
<Div id = "container">
<Div id = "car">
<Div id = "chassis"> </div>
<Div id = "backtire" class = "tire">
<Div class = "hr"> </div>
<Div class = "vr"> </div>
</Div>
<Div id = "fronttire" class = "tire">
<Div class = "hr"> </div>
<Div class = "vr"> </div>
</Div>
</Div>
<Div id = "grass"> </div>
</Div>
<Footer> </footer>
</Body>
</Html>
CSS code:
Body
{
Padding: 0;
Margin: 0;
}
Define the animation to which the car body and tires are transferred (you will see that each animation has four versions of definition: native version/webkit [Chrome | Safari]/ms [for backward compatibility with IE10]/moz [FireFox ])
The Code is as follows:
/* Define the animation: move from-400px to 1600px */
@ Keyframes carAnimation
{
0% {left:-400px;}/* specifies the initial position, 0% is equivalent to from */
100% {left: 1600px;}/* specifies the final position, 100% is equivalent */
}
/* Safari and Chrome */
@-Webkit-keyframes carAnimation
{
0% {left:-400px ;}
100% {left: 1600px ;}
}
/* Firefox */
@-Moz-keyframes carAnimation
{
0% {left:-400 ;}
100% {left: 1600px ;}
}
/* IE is not supported at the moment. It is defined here to be backward compatible with IE10 */
@-Ms-keyframes carAnimation
{
0% {left:-400px ;}
100% {left: 1600px ;}
} @ Keyframes tyreAnimation
{
0% {transform: rotate (0 );}
100% {transform: rotate (1800deg );}
}
@-Webkit-keyframes tyreAnimation
{
0% {-webkit-transform: rotate (0 );}
100% {-webkit-transform: rotate (1800deg );}
}
@-Moz-keyframes tyreAnimation
{
0% {-moz-transform: rotate (0 );}
100% {-moz-transform: rotate (1800deg );}
}
@-Ms-keyframes tyreAnimation
{
0% {-ms-transform: rotate (0 );}
100% {-ms-transform: rotate (1800deg );}
} # Container
{
Position: relative;
Width: 100%;
Height: 600px;
Overflow: hidden;/* this is very important */
}
# Car
{
Position: absolute;/* absolute positioning of vehicles in containers */
Width: 400px;
Height: 210px;/* total height of the CAR, including tires and chassis */
Z-index: 1;/* place the car above the background */
Top: 300px;/* distance from the top (Y axis )*/
Left: 50px;/* distance from the left side (X axis )*/
/* The following content gives the element a pre-defined animation and related attributes */
-Webkit-animation-name: carAnimation;/* name */
-Webkit-animation-duration: 10 s;/* duration */
-Webkit-animation-iteration-count: infinite;/* number of iterations-unlimited times */
-Webkit-animation-timing-function: linear;/* the animation is played at the same speed from start to end */
-Moz-animation-name: carAnimation;/* name */
-Moz-animation-duration: 10 s;/* duration */
-Moz-animation-iteration-count: infinite;/* number of iterations-unlimited times */
-Moz-animation-timing-function: linear;/* the animation is played at the same speed from start to end */
-Ms-animation-name: carAnimation;/* name */
-Ms-animation-duration: 10 s;/* duration */
-Ms-animation-iteration-count: infinite;/* number of iterations-unlimited times */
-Ms-animation-timing-function: linear;/* the animation is played at the same speed from start to end */
Animation-name: carAnimation;/* name */
Animation-duration: 10 s;/* duration */
Animation-iteration-count: infinite;/* number of iterations-unlimited times */
Animation-timing-function: linear;/* the animation is played at the same speed from start to end */
}
/* Body */
# Chassis
{
Position: absolute;
Width: 400px;
Height: 130px;
Background: # FF9900;
Border: 2px solid # FF6600;
}
/* Tires */
. Tire
{
Z-index: 1;/* same as above, tires should also be placed above the background */
Position: absolute;
Bottom: 0;
Border-radius: 60px;/* circle radius */
Height: 120px;/* 2 * radius = height */
Width: 120px;/* 2 * radius = width */
Background: # 0099FF;/* fill color */
Border: 1px solid # 3300FF;
-Webkit-animation-name: tyreAnimation;
-Webkit-animation-duration: 10 s;
-Webkit-animation-iteration-count: infinite;
-Webkit-animation-timing-function: linear;
-Moz-animation-name: tyreAnimation;
-Moz-animation-duration: 10 s;
-Moz-animation-iteration-count: infinite;
-Moz-animation-timing-function: linear;
-Ms-animation-name: tyreAnimation;
-Ms-animation-duration: 10 s;
-Ms-animation-iteration-count: infinite;
-Ms-animation-timing-function: linear;
Animation-name: tyreAnimation;
Animation-duration: 10 s;
Animation-iteration-count: infinite;
Animation-timing-function: linear;
}
# Fronttire
{
Right: 20px;/* set the distance between the right tire and the edge to 20 */
}
# Backtire
{
Left: 20px;/* set the distance between the left tire and the edge to 20 */
}
# Grass
{
Position: absolute;/* The background is definitely located in the container */
Width: 100%;
Height: 130px;
Bottom: 0;
/* Linear gradient of the background color. bottom indicates the starting position of the gradient. The first color value is the starting value of the gradient, and the second color value is the ending value */
Background: linear-grdaient (bottom, #33CC00, #66FF22 );
Background:-webkit-linear-gradient (bottom, #33CC00, #66FF22 );
Background:-moz-linear-gradient (bottom, #33CC00, #66FF22 );
Background:-ms-linear-gradient (bottom, #33CC00, #66FF22 );
}
. Hr,. vr
{
Position: absolute;
Background: # 3300FF;
}
. Hr
{
Height: 1px;
Width: 100%;/* tire horizontal line */
Left: 0;
Top: 60px;
}
. Vr
{
Width: 1px;
Height: 100%;/* vertical line of the tire */
Left: 60px;
Top: 0;
}
3. JQuery and CSS3
This is an effective and compatible method (especially for IE9 that does not currently support CSS3)
HTML code (we can see that it is not the same as the HTML code in CSS3 ):
The Code is as follows:
<Html>
<Head>
<Meta charset = "UTF-8"/>
<Title> Animations in HTML5 using CSS3 animations </title>
</Head>
<Body>
<Div id = "container">
<Div id = "car">
<Div id = "chassis"> </div>
<Div id = "backtire" class = "tire">
<Div class = "hr"> </div>
<Div class = "vr"> </div>
</Div>
<Div id = "fronttire" class = "tire">
<Div class = "hr"> </div>
<Div class = "vr"> </div>
</Div>
</Div>
<Div id = "grass"> </div>
</Div>
<Footer> </footer>
</Body>
</Html>
CSS:
<Style>
Body
{
Padding: 0;
Margin: 0;
}
# Container
{
Position: relative;
Width: 100%;
Height: 600px;
Overflow: hidden;/* this is very important */
}
# Car
{
Position: absolute;/* absolute positioning of vehicles in containers */
Width: 400px;
Height: 210px;/* total height of the CAR, including tires and chassis */
Z-index: 1;/* place the car above the background */
Top: 300px;/* distance from the top (Y axis )*/
Left: 50px;/* distance from the left side (X axis )*/
}
/* Body */
# Chassis
{
Position: absolute;
Width: 400px;
Height: 130px;
Background: # FF9900;
Border: 2px solid # FF6600;
}
/* Tires */
. Tire
{
Z-index: 1;/* same as above, tires should also be placed above the background */
Position: absolute;
Bottom: 0;
Border-radius: 60px;/* circle radius */
Height: 120px;/* 2 * radius = height */
Width: 120px;/* 2 * radius = width */
Background: # 0099FF;/* fill color */
Border: 1px solid # 3300FF;
-O-transform: rotate (0deg);/* rotation (unit: Degree )*/
-Ms-transform: rotate (0deg );
-Webkit-transform: rotate (0deg );
-Moz-transform: rotate (0deg );
}
# Fronttire
{
Right: 20px;/* set the distance between the right tire and the edge to 20 */
}
# Backtire
{
Left: 20px;/* set the distance between the left tire and the edge to 20 */
}
# Grass
{
Position: absolute;/* The background is definitely located in the container */
Width: 100%;
Height: 130px;
Bottom: 0;
/* Linear gradient of the background color. bottom indicates the starting position of the gradient. The first color value is the starting value of the gradient, and the second color value is the ending value */
Background: linear-grdaient (bottom, #33CC00, #66FF22 );
Background:-webkit-linear-gradient (bottom, #33CC00, #66FF22 );
Background:-moz-linear-gradient (bottom, #33CC00, #66FF22 );
Background:-ms-linear-gradient (bottom, #33CC00, #66FF22 );
}
. Hr,. vr
{
Position: absolute;
Background: # 3300FF;
}
. Hr
{
Height: 1px;
Width: 100%;/* horizontal line */
Left: 0;
Top: 60px;
}
. Vr
{
Width: 1px;
Height: 100%;/* vertical line */
Left: 60px;
Top: 0;
}
</Style>
JS Code:
First introduce the online API:
The Code is as follows:
<Script src = "https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"> </script>
Implementation of the animation code (quite concise ):
The Code is as follows:
<Script>
$ (Function (){
Var rot = 0;
Var prefix?#('.tire'}.css ('-o-transform ')? '-O-transform' :( ('.tire').css ('-ms-transform ')? '-Ms-transform' :( ('.tire').css ('-moz-transform ')? '-Moz-transform' :( ('.tire').css ('-webkit-transform ')? '-Webkit-transform': 'transform ')));
Var origin = {/* set our starting point */
Left:-400
};
Var animation = {/* This animation is executed by jQuery */
Left: 1600/* set the final position to be moved */
};
Var rotate = function () {/* This method will be called by the rotating wheel */
Rot + = 2;
Condition ('.tire'detail .css (prefix, 'rotate ('+ rot + 'deg )');
};
Var options = {/* parameters to be used by jQuery */
Easing: 'linear ',/* specifies the speed, which is linear here, that is, a uniform speed */
Duration: 10000,/* specifies the animation duration */
Complete: function (){
Certificate ('your car'}.css (origin). animate (animation, options );
},
Step: rotate
};
Options. complete ();
});
</Script>
A simple explanation: prefix first identifies which definition is currently used (-o? -Moz? -Webkit? -Ms ?), The starting and ending positions of the animation are defined. Next, define the function for setting the rotation angle (this function will be executed in every step of the animation ). Then, an animation is defined, which leads to infinite auto-cycle calls!
In this article, we use a simple animation example to demonstrate several common animation methods in HTML5.