HTML5 three ways to implement animations

Source: Internet
Author: User
Tags border color button type

Editor's note: The author takes a moving car as an example, tells about three ways to achieve HTML5 animation, clear thinking, animation is not just canvas, there are CSS3 and JavaScript. Through reasonable choice, to achieve the best implementation.

PS: The playback process may be somewhat less fluid or distorted due to the graphics card, the recorded frame interval, and the possible reasons for your computer's processor!

Implemented in three different ways:

(1) Canvas elements combined with JS

(2) Pure CSS3 animation (not supported by all major browsers such as IE)

(3) CSS3 combined with jquery

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 with canvas customizations are not optimized. The reason is that the hardware used by the browser depends primarily on the graphics card's capabilities. Currently, the browser does not give us the right to directly access the graphics card, for example, every painting operation has to call some functions in the browser first.

1.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,//x The position of the    car on the axis (will be changed)    cary=300,// Position of the car on the y-axis (will remain constant)    carwidth=400,//width of the car    carheight=130,//the height of the car    tiresdelta=15,//the distance from a tyre to the closest car chassis axisdelta=20,//the distance between the shaft of the    bottom chassis of the car and the tyre    radius=60;//the tyre radius

In order to instantiate the car canvas (initially hidden), we use the following self-executing anonymous function

(function () {   var car=document.createelement (' canvas ');//create 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 play" function by repeating the "picture car" operation at timed intervals:

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 animate 25fps[frames per second],40/ 1000, which is one-twenty fifth      s.innerhtml= ' pause ';//Rename the button to "Pause"   }

Acceleration, deceleration, by changing 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;}

How to initialize the page load:

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 () ;//save current coordinate value and state, corresponding similar "push" Operation   Drawgrass ();//Draw Background   c.translate (carx,0);//move start coordinates   drawcar ();//Draw car ( Hidden canvas)   c.drawimage (w.canvas,0,cary);//Draw the final display of the car   c.restore ();//Restore the state of the canvas, corresponding to a "pop" operation   carx+= dx;//resets the position of the car in the x-axis direction to simulate the forward walk   caralpha+=dx/radius;//proportionally increases the tyre angle   if (carx>c.canvas.width) {//Set some periodic boundary conditions      carx=-carwidth-10;//can also reverse the speed to Dx*=-1;   }}

Painting background:

function Drawgrass () {   //creates a linear gradient, the first two parameters are the start point coordinates of the gradient, and the last two are the gradient end point coordinates   var grad=c.createlineargradient (0, C.canvas.height-grassheight,0,c.canvas.height);   Specifies a gradient for a linear gradient, 0 for the starting color of the ramp, and 1 for the 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 '; /Set Border color     w.linewidth=2;//Set the width of the border, in pixels   w.fillstyle= ' #FF9900 ';//Set Fill Color   w.beginpath ();//start drawing a new path   W.rect (0,0,carwidth,carheight);//Draw a rectangle   w.stroke ();//Draw Border   W.fill ();//Fill Background   w.closepath ();//Close New Path of drawing   Drawtire (Tiresdelta+radius,carheight+axisdelta);//We began to draw the first wheel   drawtire (Carwidth-tiresdelta-radius, Carheight+axisdelta);//The same, 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 simple principle and detailed comments in the code, this is not explained here!

2.CSS3

You will see that we have completely achieved the same animation effect as above without a single JS code:

HTML code:

CSS code:

body {    padding:0;    margin:0; }

Define the motion of the body and the tyre (you will see that every animation has four versions defined: Native version/webkit "chrome| Safari "/ms" for backwards compatibility IE10 "/moz" FireFox ")

/* Define animation: move from -400px position to 1600px position */@keyframes caranimation {    0% {left:-400px;} /* Specify initial position, 0% equivalent to from*/    100% {left:1600px;} /* Specify final location, 100% equivalent to 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 not supported, defined here for backwards compatibility 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 important */} #car {Position:absolute;/* car in the container with absolute positioning */width:400px; height:210px;/* total height of the car, including tires and chassis */z-index:1;/* Let the car above the background */top:300px;/* distance from the top (y-axis) */left:50px;/* distance from the left (x-axis) */* Content gives the element predefined animations and related properties */-webkit-animation-name:caranimation;/* Name */-webkit-animation-duration:10s;/* duration */-webkit- animation-iteration-count:infinite;/* iterations-Infinite times */-webkit-animation-timing-function:linear;/* play the animation from start to finish at the same speed */- moz-animation-name:caranimation;/* name */-moz-animation-duration:10s;/* Duration */-moz-animation-iteration-count: infinite;/* iterations-Infinite times */-moz-animation-timing-function:linear;/* play the animation from start to finish at the same speed */-ms-animation-name:caranimation ;/* Name */-ms-animation-duration:10s;/* Duration */-ms-animation-iteration-count:infinite;/* Iteration number-infinite times */-ms-animation-tim ing-function:linear;/* play the animation from beginning to end at the same speed */animation-name:caranimation;/* Name */animation-duration:10s;/* duration */animation-iteration-count:infinite;/* iterations-Unlimited */animation-timing-function:linear;/* play the animation from beginning to end at the same speed */}/* Body/#chassis    {Position:absolute;    width:400px;    height:130px;    Background: #FF9900; border:2px solid #FF6600;    }/* tires */. Tire {z-index:1;/*, 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 of the tyre distance to the edge is 20*/} #backtire {left:20px;/* set the distance from the left edge of the tyre to 20*/} #grass {position    : absolute;/* background absolutely positioned in the container */width:100%;    height:130px;    bottom:0;    /* Let the background color linear gradient, bottom, indicate the beginning of the gradient, the first color value is the starting value of the gradient, the second color value is the terminating 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 tires * * left:0; top:60px;    }. VR {width:1px;    height:100%;/* vertical line of tires */left:60px; top:0; }
3.JQuery and CSS3

This is an effective and compatible way (especially for IE9 temporarily does not support CSS3)

The HTML code (which you can see is not different from the HTML code in CSS3):

Css:

<style> body {padding:0;         margin:0;    } #container {position:relative;    width:100%;    height:600px;    overflow:hidden;/* This is important */} #car {Position:absolute;/* car in the container with absolute positioning */width:400px; height:210px;/* total height of the car, including tires and chassis */z-index:1;/* Let the car above 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;    }/* tires */. Tire {z-index:1;/*, 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: degrees) */-ms-transform:rotate (0DEG);    -webkit-transform:rotate (0DEG); -moz-transform:rotate (0DEG); } #fronttire {right:20px;/* set the distance to the right of the tyre distance to the edge is 20*/} #backtire {left:20px;/* set the distance from the left edge of the tyre to 20*/} #grass {position : absolute;/* Background Absolutely setBits in the container */width:100%;    height:130px;    bottom:0;    /* Let the background color linear gradient, bottom, indicate the beginning of the gradient, the first color value is the starting value of the gradient, the second color value is the terminating 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:

<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={/* the animation is executed by jquery */left:1600/* Set the final position we will move to */};     var rotate=function () {/* The method will be rotated by the wheel called */rot+=2; $ ('. Tire '). CSS (prefix, ' rotate (' +rot+ ' deg) ');};     var options={/* the parameters to be used by jquery */easing: ' linear ',/* Specify the speed, here is only linear, that is, constant velocity */duration:10000,/* Specify the duration of the animation */complete:function () {    $ (' #car '). CSS (Origin). Animate (Animation,options);}, step:rotate};     Options.complete ();  });      </script>

Simple explanation: prefix first identifies which definition is currently being 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, which is performed in each step of the animation (step). Then, an animation is defined that results in an infinite self-looping call!

This paper, through a simple animation example, demonstrates several common ways to implement animation under HTML5.

Original:HTTP://blog.csdn.net/yanghua_kobe/article/details/7226816

HTML5 three ways to implement animations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.