Summary of ways to achieve animation effects in HTML5 _html5 tutorial skills
WBOY
Release: 2016-05-16 15:45:59
Original
1606 people have browsed it
The editor uses a moving car as an example to describe three ways to implement HTML5 animation. The ideas are clear. Animation is not only canvas, but also css3 and javascript. Through reasonable choices, the optimal implementation can be achieved.
PS: Due to the graphics card, recording frame interval, and possibly your computer processor, the playback process may be a little unsmooth or distorted! It can be implemented in three ways: (1) Canvas element combined 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 the <canvas> element: because the browser can optimize the performance of those elements (usually their styles, such as CSS) , but the effect we use to customize the drawing using canvas cannot be optimized. The reason is again that the hardware used by the browser mainly depends on the capabilities of the graphics card. Currently, the browser does not give us direct access to the graphics card. For example, every drawing operation must first call certain functions in the browser. 1.canvas html code:
Copy code
The code is as follows:
Animation in HTML5 using the canvas element
js code: Define some variables:
Copy code
The code is as follows :
var dx=5, //Current rate rate=1, //Current playback speed ani, //Current animation loop c, //Drawing ( Canvas Context) w, //Car [hidden](Canvas Context) grassHeight=130, //Background height carAlpha=0, //Tire rotation angle carX=-400 , //The position of the car in the x-axis direction (will be changed) carY=300, //The position of the car in the y-axis direction (will remain constant) carWidth=400, //The width of the car carHeight=130, //The height of the car tiresDelta=15, //The distance from one tire to the closest car chassis axisDelta=20, //The distance between the axis of the bottom chassis of the car and the tire radius=60; //radius of tire
To instantiate the car canvas (which is initially hidden), we use the following self-executing anonymous function
Copy code
The code is as follows:
(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 the "Play" button to simulate the "frame playback" function by repeatedly executing the "draw car" operation at regular intervals:
Copy code
The code is as follows:
function play(s){ //The parameter s is a button if(ani){ //If ani is not null, it represents us There is already an animation clearInterval(ani); //so we need to clear it (stop the 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, which is one-twenty-fifth s.innerHTML='Pause'; //Rename the button to "Pause" } }
Acceleration and deceleration are achieved by changing the moving distance through the following methods:
Copy the code
The code is as follows :
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() ; }
Main method:
Copy code
The code is as follows:
function drawCanvas (){ c.clearRect(0,0,c.canvas.width, c.canvas.height); //Clear the Canvas (displayed) to avoid errors c.save(); / /Save the current coordinate values and status, corresponding to similar "push" operations drawGrass(); //Draw the background c.translate(carX,0); //Move the starting point coordinates drawCar(); //Draw a car (hidden canvas) c.drawImage(w.canvas,0,carY); //Draw the car that is finally displayed c.restore(); //Restore the state of the Canvas, corresponding It is similar to the "pop" operation carX =dx; //Reset the position of the car in the X-axis direction to simulate walking forward carAlpha =dx/radius; //Increase the tire angle proportionally if (carX>c.canvas.width){ //Set some regular boundary conditions carX=-carWidth-10; //You can also reverse the speed to dx*=-1; } }
Draw background:
Copy code
The code is as follows:
function drawGrass( ){ //Create a linear gradient. The first two parameters are the coordinates of the gradient start point, and the last two parameters are the coordinates of the gradient end point. var grad=c.createLinearGradient(0,c.canvas.height-grassHeight,0 ,c.canvas.height); //Specify the gradient color for the linear gradient, 0 represents the gradient starting color, 1 represents the gradient ending 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); }
Draw the car body:
Copy the code
The code is as follows:
function drawCar( ){ w.clearRect(0,0,w.canvas.width,w.canvas.height); //Clear the hidden artboard w.strokeStyle='#FF6600'; //Set the border color w.lineWidth=2; //Set the width of the border in pixels w.fillStyle='#FF9900'; //Set the fill color w.beginPath(); //Start drawing 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 drawn drawTire(tiresDelta radius,carHeight axisDelta); //We start drawing the first wheel drawTire(carWidth-tiresDelta-radius,carHeight axisDelta); / /Similarly, the second }
Since the principle is simple and detailed comments are made in the code, I won’t explain them one by one here! 2.CSS3 You will see that we have completely achieved the same animation effect as above without a single JS code: HTML code :
Copy the code
The code is as follows:
Animations in HTML5 using CSS3 animations
< div class="vr">
CSS code : body { padding:0; margin:0; }
Define the animation of body and tire rotation (you will see that basically every animation has four versions of definition: native version/webkit[Chrome|Safari]/ms[for backward compatibility with IE10]/moz[FireFox 】)
Copy the code
The code is as follows:
/*Define animation: move from -400px position to 1600px position*/ @keyframes carAnimation { 0% { left:-400px; } /* Specify the initial position , 0% is equivalent to from*/ 100% { left:1600px; } /* Specifies the final position, 100% is 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 does not support this yet. This definition is for Back 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; / *The car is positioned absolutely in the container*/ width:400px; height:210px; /*The total height of the car, including tires and chassis*/ z-index:1; /*Let the car Above the background*/ top:300px; /*Distance from top (y-axis)*/ left:50px; /*Distance from left (x-axis)*/ /* The following content gives the element predefined animation and related attributes*/ -webkit-animation-name:carAnimation; /*name*/ -webkit-animation-duration:10s; /*duration*/ -webkit-animation-iteration-count:infinite; /*Number of iterations-infinite*/ -webkit-animation-timing-function:linear; /*Play animation at the same speed from beginning to end* / -moz-animation-name:carAnimation; /*name*/ -moz-animation-duration:10s; /*duration*/ -moz-animation-iteration-count:infinite; /*Number of iterations - unlimited*/ -moz-animation-timing-function:linear; /*Play animation at the same speed from beginning to end*/ -ms-animation-name:carAnimation; /*Name*/ -ms-animation-duration:10s; /*Duration*/ -ms-animation-iteration-count:infinite; /*Number of iterations-infinite*/ - ms-animation-timing-function:linear; /*Play animation at the same speed from beginning to end*/ animation-name:carAnimation; /*Name*/ animation-duration:10s; /* Duration*/ animation-iteration-count:infinite; /*Number of iterations-infinite*/ animation-timing-function:linear; /*Play animation at the same speed from beginning to end*/ } /*body*/ #chassis { position:absolute; width:400px; height:130px; background:#FF9900; border: 2px solid #FF6600; } /*Tire*/ .tire { z-index:1; /*Same as above, the tire should also be placed in the background above*/ 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 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 absolutely positioned in the container*/ width:100%; height:130px; bottom:0; /*Let the background color linearly gradient, bottom, represents the starting point of the gradient, the first color value is the starting value of the gradient, 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 of tire*/ left:0 ; top:60px; } .vr { width:1px; height:100%; /*Vertical line of tire*/ left:60px; top:0; }
3.JQuery and CSS3 This is a method with good effect and compatibility (especially since IE9 does not support CSS3 yet) HTML code (You can see that it is no different from the HTML code in CSS3):
Copy the code
The code is as follows:
Animations in HTML5 using CSS3 animations
< div class="vr">
CSS:
JS code: First introduce the online API:
Copy code
code As follows:
Implement animation code (quite concise):
Copy the code
The code is as follows:
<script> <br>$(function(){ <br>var rot=0; <br>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'))); <br>var origin={ /*Set our starting point*/ <br>left:-400 <br>}; <br>var animation={ /*The animation is performed by jQuery*/ <br>left:1600 /*Set the position we will move to The final position*/ <br>}; <br>var rotate=function(){ /*This method will be called by the rotated wheel*/ <br>rot =2; <br>$('.tire'). css(prefix,'rotate(' rot 'deg)'); <br>}; <br>var options={ /*Parameters to be used by jQuery*/ <br>easing:'linear', /*Specify speed , here it is just linear, that is, uniform speed*/ <br>duration:10000, /*Specify animation duration*/ <br>complete:function(){ <br>$('#car').css(origin) .animate(animation,options); <br>}, <br>step:rotate <br>}; <br>options.complete(); <br>}); <br></script>
Simple explanation: prefix first identifies which definition is currently used (-o?-moz?-webkit?-ms?), and then defines the starting position and end position of the animation. Next, a function is defined that sets the rotation angle (this function will be executed at each step of the animation). Then, an animation is defined in a way that results in an infinite self-loop call! This article, through a simple animation example, demonstrates several common ways to implement animation under HTML5.
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn