HTML5 is becoming more and more popular. In an era of growing mobile devices, the need to retrofit flash plug-ins from Adobe is also growing rapidly. Because just recently, Adobe announced that Flash will no longer support mobile devices. This means that Adobe itself believes that HTML5 is an important technology for mobile devices. And the change of desktop system is a matter of sooner or later.
One of the big disadvantages of HTML is the lack of support for multimedia technology. In HTML, you can't directly display a video or paint on the screen. In HTML5, with the introduction of <video> and <canvas> elements. These elements give developers the possibility of using "pure" HTML to implement multimedia technology-just write some JavaScript code to fit the HTML. In multimedia technology, there is a basic technology should be supported-animation. In HTML5, there are a number of ways to implement this functionality.
In this article, I will only compare the latest <canvas> elements with the upcoming CSS3 animation technology. Other possibilities include the creation and animation of DOM elements or SVG elements. These possibilities will not be discussed in this article. It should be noted from the outset that canvas technology is supported in most of the current major browsers, while CSS3 animations are only possible in the latest Firefox and Chrome browsers, and the next version of IE will also provide support for CSS3 animations. (so the effect of all the demo code in this article is achievable in the current newest Chrome browser under the Win 7 system, but not all of the demo code can be seen in other operating systems and other browsers).
Here I chose a relatively simple animation:
PS: The playback process may be less fluid or distorted due to the video card, the frame spacing of the recording, and possibly the reason for your computer's processor.
Implemented in three ways:
(1) Canvas elements combined with JS
(2) Pure CSS3 animation (not to be supported by all major browsers, IE)
(3) CSS3 combined with jquery implementation
Knowing how to use CSS3 animations is more important than knowing how to use <canvas> elements: Because browsers can optimize the performance of those elements (usually their style, such as CSS), and the effects we use to canvas custom drawings are not optimized. The reason is that the hardware used by the browser depends primarily on the capabilities of the graphics card. At present, the browser does not give us the right to access the video card directly, for example, each painting operation has to call some functions in the browser first.
let's start with the canvas .
HTML code:
JS Code:
Define some variables:
var dx=5, //Current rate
rate=1, //Current playback speed
ANI, //Current animation loop
C,/ /Paint (Canvas context)
W, / /car [hidden] (Canvas
context) grassheight=130,// background height
caralpha=0,// tyre rotation angle
carx=-400, The position of the car (to be changed) in the x-axis direction (will be altered) cary=300 the position of the car in the //y axis (will remain constant)
carwidth=400, //width of the car
carheight=130 ,// car height
tiresdelta=15,// distance from one tyre to the nearest car chassis
axisdelta=20,// car bottom chassis shaft with tyre distance
radius=60; The radius of the tyre
To instantiate the car canvas (initially hidden), we use the following self executed anonymous function
(function () {
var car=document.createelement (' canvas '); Create an element
Car.height=carheight+axisdelta+radius; Set height
car.width=carwidth; Set width
w=car.getcontext (' 2d ');
}) ();
Click on the "Play" button to simulate the "frame playing" function by repeating the "draw car" operation regularly:
function Play (s) { //parameter S is a button
if (ANI) { //if ANI is not NULL, it means that we currently have an animated
clearinterval (ANI); So we need to clear it (stop animation)
Ani=null;
S.innerhtml= ' play '; Rename the button to "play"
}else{
ani=setinterval (drawcanvas,40); We will set the animation to 25fps[frames per second],40/1000, that is one-twenty fifth
s.innerhtml= ' Pause '; Rename the button to pause}
}
Accelerate, decelerate, and change the size of the moving distance to achieve the following methods:
function speed (delta) {
var newrate=math.max (rate+delta,0.1);
DX=NEWRATE/RATE*DX;
rate=newrate;
}
Initialization method for page loading:
init
function init () {
C=document.getelementbyid (' canvas '). GetContext (' 2d ');
Drawcanvas ();
}
Keynote method:
function Drawcanvas () {
c.clearrect (0,0,c.canvas.width, c.canvas.height); Clear Canvas (shown) to avoid error
c.save (); Saves the current coordinate value as well as the state, corresponding to the "push" Operation
Drawgrass (); Draw Background
c.translate (carx,0); Move start coordinate
drawcar (); Draw the car (hidden canvas)
c.drawimage (w.canvas,0,cary); Draw the final display of the car
c.restore (); Restores the canvas state, corresponding is similar "pops" the Operation
Carx+=dx; Reset the position of the car in the direction of the x-axis to simulate forward
Caralpha+=dx/radius; Proportionally increasing the tyre angle
if (carx>c.canvas.width) { //setting certain periodic boundary conditions
carx=-carwidth-10; You can also reverse the speed to dx*=-1
}
Drawing background:
function Drawgrass () {
//create a linear gradient, the first two parameters are the gradient start point coordinates, the last two are the gradient end point coordinates
var grad=c.createlineargradient (0, C.canvas.height-grassheight,0,c.canvas.height);
Specifies gradients for linear gradients, 0 for gradient start color, 1 for gradient stop color
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);
}
Painting Body:
function Drawcar () {
w.clearrect (0,0,w.canvas.width,w.canvas.height); Empty the hidden artboard
w.strokestyle= ' #FF6600 '; Sets the border color
w.linewidth=2; Sets the width of the border, in pixels
w.fillstyle= ' #FF9900 '; Set the fill Color
w.beginpath (); Start drawing New Path
w.rect (0,0,carwidth,carheight); Draw a rectangular
w.stroke (); Draw a Border
W.fill (); Fill background
w.closepath (); Closes the drawn new path
drawtire (Tiresdelta+radius,carheight+axisdelta); We began to draw the first wheel
drawtire (Carwidth-tiresdelta-radius,carheight+axisdelta); Similarly, the second
}
Draw Tires:
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 (0,0,radius,0,2*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 ();
}
Because of the simplicity of the principle and the detailed comments in the code, this is not explained here.
It's CSS3.
You will see that we have not passed a JS code to fully achieve the same animation as above:
HTML code:
CSS code:
Body
{
padding:0;
margin:0;
}
Define the animation of the body and tyre (you will see that basically each animation has four versions of the definition: Native version/webkit "chrome| Safari "/ms" for backwards compatibility IE10 "/moz" FireFox)
/* Define animation: Move from the position of -400px to 1600px
/@keyframes caranimation
{
0% {left:-400px;} /* Specifies the initial position, 0% is equivalent to from*/
100% {left:1600px;} /* Specify the final location, 100% equals to*/
}/
* Safari and Chrome * *
@-webkit-keyframes caranimation
{
0% {left:- 400px; }
100% {left:1600px}}
/* Firefox
/@-moz-keyframes caranimation
{
0% {left:-400;}
100% {left:1600px}
}
/*ie is temporarily unsupported and is defined here for backward compatibility 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 very important/} #car {Position:absolute;
* * Vehicle in the container using absolute positioning * * * width:400px; height:210px; /* The total height of the vehicle, including tires and chassis * * * Z-INDEX:1; * * Let the car on the top of the background/top:300px; /* distance from the top (Y axis) * * * left:50px; /* Distance to the left (x axis)////////* The following content gives the element a predefined animation and related attributes * *-webkit-animation-name:caranimation; * * Name/-webkit-animation-duration:10s; /* Duration */-webkit-animation-iteration-count:infinite; /* Iterative number-UNLIMITED times * * *-webkit-animation-timing-function:linear; /* Play the animation from beginning to end with the same speed * * *-moz-animation-name:caranimation; * * Name/-moz-animation-duration:10s; /* Duration */-moz-animation-iteration-count:infinite; /* Iterative number-UNLIMITED times * * *-moz-animation-timing-function:linear; /* Play the animation from beginning to end with the same speed * * *-ms-animation-name:caranimation; * * Name/-ms-animation-duration:10s; /* Duration */-ms-animation-iteration-count:infinite; /* Iterative number-UNLIMITED times * * *-ms-animation-timing-function:linear; /*Play the animation from beginning to end with the same speed * * * animation-name:caranimation; * * Name/animation-duration:10s; /* Duration */animation-iteration-count:infinite; /* Iterative number-UNLIMITED times * * * animation-timing-function:linear;
/* Play the animation from beginning to end with the same speed * * * * Body/#chassis {position:absolute;
width:400px;
height:130px;
Background: #FF9900;
border:2px solid #FF6600; * * * Tyre/* Tire {z-index:1;
* Ditto, 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:10s;
-webkit-animation-iteration-count:infinite;
-webkit-animation-timing-function:linear;
-moz-animation-name:tyreanimation;
-moz-animation-duration:10s;
-moz-animation-iteration-count:infinite;
-moz-animation-timing-function:linear; -ms-animation-name:tyreanimation;
-ms-animation-duration:10s;
-ms-animation-iteration-count:infinite;
-ms-animation-timing-function:linear;
Animation-name:tyreanimation;
animation-duration:10s;
Animation-iteration-count:infinite;
Animation-timing-function:linear; } #fronttire {right:20px; /* Set the distance to the right tire distance to the edge of 20*/} #backtire {left:20px;
/* Set the distance to the left tire distance of 20*/} #grass {position:absolute;/* Background absolutely positioned in the container * * * width:100%;
height:130px;
bottom:0;
/* Let the background color linear gradient, bottom, indicates the beginning of the gradient, the first color value is the starting value of the gradient, the second color value is the termination 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%;
/* The horizontal line of the tire * * LEFT:0;
top:60px;
} . VR {width:1px; height:100%;
* * Tire vertical Line/left:60px;
top:0; }
jquery and CSS3
This is an effective and compatible way (especially for IE9 temporarily does not support CSS3)
HTML code (you can see no different from the HTML code in CSS3):
Css:
<style> body {padding:0;
margin:0;
} #container {position:relative;
width:100%;
height:600px; Overflow:hidden; /* This very important/} #car {Position:absolute;
* * Vehicle in the container using absolute positioning * * * width:400px; height:210px; /* The total height of the vehicle, including tires and chassis * * * Z-INDEX:1; * * Let the car on the top of the background/top:300px; /* distance from the top (Y axis) * * * left:50px;
/* Distance from the Left (x axis) * * * * Body/#chassis {position:absolute;
width:400px;
height:130px;
Background: #FF9900;
border:2px solid #FF6600; * * * Tyre/* Tire {z-index:1;
* Ditto, 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);
/* Rotate (unit: degree) * *-ms-transform:rotate (0DEG);
-webkit-transform:rotate (0DEG);
-moz-transform:rotate (0DEG);
} #fronttire {right:20px; /* Set the distance to the right tire distance to the edge of 20*/} #backtire {left:20px;
/* Set the distance to the left tire distance of 20*/} #grass {position:absolute;/* Background absolutely positioned in the container * * * width:100%;
height:130px;
bottom:0;
/* Let the background color linear gradient, bottom, indicates the beginning of the gradient, the first color value is the starting value of the gradient, the second color value is the termination 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:
Introduce the online API first:
<script src= "Https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" ></script>
Implementing animation code (fairly concise):
<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 performed by
jquery /left:1600/* Set the final position we will move to
;
var rotate=function () {/ * This method will be called by the rotating wheel/
rot+=2;
$ ('. Tire '). CSS (prefix, ' rotate (' +rot+ ' deg) ');
var options={ /* will be used by jquery parameters * * *
easing: ' linear ',/ * specified speed, here is linear, that is, uniform/
duration:10000, / * Specify animation duration/
complete:function () {
$ (' #car '). CSS (Origin). Animate (Animation,options);
},
step:rotate
};
Options.complete ();
});
</script>
Simple explanation: prefix first identifies which definition is currently adopted (-o?-moz?-webkit?-ms?), and then defines the starting and ending positions of the animation. Next, you define a function that sets the rotation angle (the function will be executed in each step of the animation). Then, you define an animation that causes an infinite loop call.
This paper, through a simple animation example, demonstrates several common ways to realize animation under HTML5.
Source Download