HTML5实现动画三种方式

HTML5实现动画三种方式

编者注:作者以一个运动的小车为例子,讲述了三种实现HTML5动画的方式,思路清晰,动画不仅仅是Canvas,还有css3和javascript.通过合理的选择,来实现最优的实现。

《HTML5实现动画三种方式》

PS:由于显卡、录制的帧间隔,以及可能你电脑处理器的原因,播放过程可能有些不太流畅或者失真!

分三种方式实现:

(1)   canvas元素结合JS

(2)   纯粹的CSS3动画(暂不被所有主流浏览器支持,比如IE)

(3)   CSS3结合Jquery实现

知道如何使用CSS3动画比知道如何使用<canvas>元素更重要:因为浏览器能够优化那些元素的性能(通常是他们的样式,比如CSS),而我们使用canvas自定义画出来的效果却不能被优化。原因又在于,浏览器使用的硬件主要取决于显卡的能力。目前,浏览器没有给予我们直接访问显卡的权力,比如,每一个绘画操作都不得不在浏览器中先调用某些函数。

1.canvas

HTML代码:

<html> 
<head>
<meta charset="UTF-8" />
<title>Animation in HTML5 using the canvas element</title>
</head>
<body οnlοad="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" οnclick="speed(-0.1);">Slower</button>
<button type="button" οnclick="play(this);">Play</button>
<button type="button" οnclick="speed(+0.1)">Faster</button>
</div>
</body>
</html>

JS代码:

定义一些变量:

var dx=5,          //当前速率 
rate=1, //当前播放速度
ani, //当前动画循环
c, //画图(Canvas Context)
w, //汽车[隐藏的](Canvas Context)
grassHeight=130, //背景高度
carAlpha=0, //轮胎的旋转角度
carX=-400, //x轴方向上汽车的位置(将被改变)
carY=300, //y轴方向上汽车的位置(将保持为常量)
carWidth=400, //汽车的宽度
carHeight=130, //汽车的高度
tiresDelta=15, //从一个轮胎到最接近的汽车底盘的距离
axisDelta=20, //汽车底部底盘的轴与轮胎的距离
radius=60; //轮胎的半径

为了实例化汽车canvas(初始时被隐藏),我们使用下面的自执行的匿名函数

(function(){ 
var car=document.createElement('canvas'); //创建元素
car.height=carHeight+axisDelta+radius; //设置高度
car.width=carWidth; //设置宽度
w=car.getContext('2d');
})();

点击“Play”按钮,通过定时重复执行“画汽车”操作,来模拟“帧播放”功能:

function play(s){               //参数s是一个button 
if(ani){ //如果ani不为null,则代表我们当前已经有了一个动画
clearInterval(ani); //所以我们需要清除它(停止动画)
ani=null;
s.innerHTML='Play'; //重命名该按钮为“播放”
}else{
ani=setInterval(drawCanvas,40); //我们将设置动画为25fps[帧每秒],40/1000,即为二十五分之一
s.innerHTML='Pause'; //重命名该按钮为“暂停”
}
}

加速,减速,通过以下方法,改变移动距离的大小来实现:

function speed(delta){ 
var newRate=Math.max(rate+delta,0.1);
dx=newRate/rate*dx;
rate=newRate;
}

页面加载的初始化方法:

//init 
function init(){
c=document.getElementById('canvas').getContext('2d');
drawCanvas();
}

主调方法:

function drawCanvas(){ 
c.clearRect(0,0,c.canvas.width, c.canvas.height); //清除Canvas(已显示的),避免产生错误
c.save(); //保存当前坐标值以及状态,对应的类似“push”操作

       drawGrass();                     //画背景
       c.translate(carX,0);                 //移动起点坐标
       drawCar();                       //画汽车(隐藏的canvas)
       c.drawImage(w.canvas,0,carY);            //画最终显示的汽车
       c.restore();                     //恢复Canvas的状态,对应的是类似“pop”操作
       carX+=dx;                        //重置汽车在X轴方向的位置,以模拟向前走
       carAlpha+=dx/radius;                 //按比例增加轮胎角度

       if(carX&gt;c.canvas.width){              //设置某些定期的边界条件
          carX=-carWidth-10;                //也可以将速度反向为dx*=-1;
       }
    }</pre><p>画背景:</p><pre class="javascript">function drawGrass(){
       //创建线性渐变,前两个参数为渐变开始点坐标,后两个为渐变结束点坐标
       var grad=c.createLinearGradient(0,c.canvas.height-grassHeight,0,c.canvas.height);
       //为线性渐变指定渐变色,0表示渐变起始色,1表示渐变终止色
       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);

    }</pre><p>画车身:</p><pre class="javascript">function drawCar(){
       w.clearRect(0,0,w.canvas.width,w.canvas.height);     //清空隐藏的画板
       w.strokeStyle='#FF6600';                 //设置边框色
       w.lineWidth=2;                       //设置边框的宽度,单位为像素
       w.fillStyle='#FF9900';                   //设置填充色
       w.beginPath();                       //开始绘制新路径
       w.rect(0,0,carWidth,carHeight);              //绘制一个矩形
       w.stroke();                          //画边框
       w.fill();                            //填充背景
       w.closePath();                       //关闭绘制的新路径
       drawTire(tiresDelta+radius,carHeight+axisDelta);     //我们开始画第一个轮子
       drawTire(carWidth-tiresDelta-radius,carHeight+axisDelta);    //同样的,第二个

    }</pre><p>画轮胎:</p><pre class="javascript">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();

    }</pre><p>由于原理简单,并且代码中作了详细注释,这里就不一一讲解!</p><h3 id="t2"><a name="t2"></a><span style="font-size: 18px;">2.CSS3</span></h3><p><span style="font-size: 10px;">你将看到我们未通过一句JS代码就完全实现了和上面一样的动画效果:</span></p><p><span style="font-size: 10px;">HTML代码:</span></p><pre class="html">&lt;html&gt;

<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代码:

 body 
{
padding:0;
margin:0;
}

定义车身与轮胎转到的动画(你会看到基本每一个动画都有四个版本的定义:原生版本/webkit【Chrome|Safari】/ms【为了向后兼容IE10】/moz【FireFox】)

 /定义动画:从-400px的位置移动到1600px的位置 / 
@keyframes carAnimation
{
0% { left:-400px; } /* 指定初始位置,0%等同于from*/
100% { left:1600px; } /* 指定最终位置,100%等同于to*/
}
 /* Safari and Chrome */ @-webkit-keyframes carAnimation { 0% {left:-400px; } 100% {left:1600px; } } /* Firefox */ @-moz-keyframes carAnimation { 0% {left:-400; } 100% {left:1600px; } } /*IE暂不支持,此处定义是为了向后兼容IE10*/ @-ms-keyframes carAnimation { 0% {left:-400px; } 100%{left:1600px; } }</pre><pre class="css" style="font-size: 10px;"> @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); } }</pre><pre class="css" style="font-size: 10px;"> #container { position:relative; width:100%; height:600px; overflow:hidden; /*这个很重要*/ } #car { position:absolute; /*汽车在容器中采用绝对定位*/ width:400px; height:210px; /*汽车的总高度,包括轮胎和底盘*/ z-index:1; /*让汽车在背景的上方*/ top:300px; /*距顶端的距离(y轴)*/ left:50px; /*距左侧的距离(x轴)*/ /*以下内容赋予该元素预先定义的动画及相关属性*/ -webkit-animation-name:carAnimation; /*名称*/ -webkit-animation-duration:10s; /*持续时间*/ -webkit-animation-iteration-count:infinite; /*迭代次数-无限次*/ -webkit-animation-timing-function:linear; /*播放动画时从头到尾都以相同的速度*/ -moz-animation-name:carAnimation; /*名称*/ -moz-animation-duration:10s; /*持续时间*/ -moz-animation-iteration-count:infinite; /*迭代次数-无限次*/ -moz-animation-timing-function:linear; /*播放动画时从头到尾都以相同的速度*/ -ms-animation-name:carAnimation; /*名称*/ -ms-animation-duration:10s; /*持续时间*/ -ms-animation-iteration-count:infinite; /*迭代次数-无限次*/ -ms-animation-timing-function:linear; /*播放动画时从头到尾都以相同的速度*/ animation-name:carAnimation; /*名称*/ animation-duration:10s; /*持续时间*/ animation-iteration-count:infinite; /*迭代次数-无限次*/ animation-timing-function:linear; /*播放动画时从头到尾都以相同的速度*/ } /*车身*/ #chassis { position:absolute; width:400px; height:130px; background:#FF9900; border: 2px solid #FF6600; } /*轮胎*/ .tire { z-index:1; /*同上,轮胎也应置于背景的上方*/ position:absolute; bottom:0; border-radius:60px; /*圆半径*/ height:120px; /* 2*radius=height */ width:120px; /* 2*radius=width */ background:#0099FF; /*填充色*/ 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; /*设置右边的轮胎距离边缘的距离为20*/ } #backtire { left:20px; /*设置左边的轮胎距离边缘的距离为20*/ } #grass { position:absolute; /*背景绝对定位在容器中*/ width:100%; height:130px; bottom:0; /*让背景色线性渐变,bottom,表示渐变的起始处,第一个颜色值是渐变的起始值,第二个颜色值是终止值 */ 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%; /*轮胎的水平线*/ left:0; top:60px; } .vr { width:1px; height:100%; /*轮胎的垂直线*/ left:60px; top:0; }</pre><h3 id="t3"><a name="t3"></a><span style="font-size: 18px;">3.JQuery与CSS3</span></h3><p><span style="font-size: 10px;">这是一个效果与兼容性俱佳的方式(特别对于IE9暂不支持CSS3而言)</span></p><p><span style="font-size: 10px;">HTML代码(可以看到与CSS3中的HTML代码并无不同):</span></p><pre class="html">&lt;html&gt; 

<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; /*这个很重要*/ } #car { position:absolute; /*汽车在容器中采用绝对定位*/ width:400px; height:210px; /*汽车的总高度,包括轮胎和底盘*/ z-index:1; /*让汽车在背景的上方*/ top:300px; /*距顶端的距离(y轴)*/ left:50px; /*距左侧的距离(x轴)*/ } /*车身*/ #chassis { position:absolute; width:400px; height:130px; background:#FF9900; border: 2px solid #FF6600; } /*轮胎*/ .tire { z-index:1; /*同上,轮胎也应置于背景的上方*/ position:absolute; bottom:0; border-radius:60px; /*圆半径*/ height:120px; /* 2*radius=height */ width:120px; /* 2*radius=width */ background:#0099FF; /*填充色*/ border:1px solid #3300FF; -o-transform:rotate(0deg); /*旋转(单位:度)*/ -ms-transform:rotate(0deg); -webkit-transform:rotate(0deg); -moz-transform:rotate(0deg); } #fronttire { right:20px; /*设置右边的轮胎距离边缘的距离为20*/ } #backtire { left:20px; /*设置左边的轮胎距离边缘的距离为20*/ } #grass { position:absolute; /*背景绝对定位在容器中*/ width:100%; height:130px; bottom:0; /*让背景色线性渐变,bottom,表示渐变的起始处,第一个颜色值是渐变的起始值,第二个颜色值是终止值 */ 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%; /*水平线*/ left:0; top:60px; } .vr { width:1px; height:100%; /*垂直线*/ left:60px; top:0; } &lt;/style&gt;</pre><p>JS代码:</p><p><span style="font-size: 10px;">首先引入在线API:</span></p><pre class="javascript">&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"&gt;&lt;/script&gt;</pre><p>实现动画代码(相当简洁):</p><pre class="javascript">&lt;script&gt; $(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={ /*设置我们的起始点*/ left:-400 }; var animation={ /*该动画由jQuery执行*/ left:1600 /*设置我们将移动到的最终位置*/ }; var rotate=function(){ /*该方法将被旋转的轮子调用*/ rot+=2; $('.tire').css(prefix,'rotate('+rot+'deg)'); }; var options={ /*将要被jQuery使用的参数*/ easing:'linear', /*指定速度,此处只是线性,即为匀速*/ duration:10000, /*指定动画持续时间*/ complete:function(){ $('#car').css(origin).animate(animation,options); }, step:rotate }; options.complete(); }); &lt;/script&gt;</pre><p>简单讲解:prefix首先识别出当前是哪个定义被采用了(-o?-moz?-webkit?-ms?),然后定义了动画的起点位置和终点位置。接着,定义了设置旋转角度的函数(该函数将在在动画的每一步(step)中执行)。然后,定义了一个动画,该定义方式导致了无限自循环调用!</p><p>本文,通过一个简单的动画实例,演示了<span class="wp_keywordlink_affiliate"><a href="http://caibaojian.com/t/html5" title="View all posts in HTML5" target="_blank">HTML5</a></span>下,实现动画的几种常见方式。</p><p>原文:http://blog.csdn.net/yanghua_kobe/article/details/7226816</p><div class="yarpp-related"><h3 class="widget-title">推荐文章</h3><ul><li><a href="http://caibaojian.com/css3-round.html" rel="bookmark">CSS3制作圆环进度动画效果</a></li><li><a href="http://caibaojian.com/css3-radial-progress-bar.html" rel="bookmark">纯CSS3实现圆弧(圆圈)百分比动画进度条</a></li><li><a href="http://caibaojian.com/jquery-circular-progress.html" rel="bookmark">jquery圆环百分比进度条制作</a></li><li><a href="http://caibaojian.com/css3-animate-spin.html" rel="bookmark">CSS揭秘之沿着环形路径运动的动画</a></li><li><a href="http://caibaojian.com/pure-css-icons.html" rel="bookmark">神奇的纯CSS图标</a></li></ul></div></div><div class="entry-details" itemprop="copyrightHolder" itemtype="http://schema.org/Organization" itemscope=""> 原创文章:<a href="http://caibaojian.com/3-html5-animations.html" rel="bookmark">HTML5实现动画三种方式</a> ,未经许可,禁止转载,<a target="_blank" href="http://caibaojian.com/copyright">©版权所有</a>。<br> 原文出处:前端开发博客 (<a href="http://caibaojian.com/3-html5-animations.html" title="HTML5实现动画三种方式">http://caibaojian.com/3-html5-animations.html</a>)</div><div class="da_container"> <img class="inner-box" src="http://caibaojian.com/a/a3.png"></div></div><div class="entry-footer clearfix" role="toolbar"><div class="bd-share"><div class="bdsharebuttonbox bdshare-button-style1-24" data-bd-bind="1504845402208"><a class="bds_qzone" data-cmd="qzone" title="分享到QQ空间"></a><a class="bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a><a class="bds_weixin" data-cmd="weixin" title="分享到微信"></a><a class="bds_more" data-cmd="more"></a></div><script>var share_excerpt = '【HTML5实现动画三种方式】编者注:作者以一个运动的小车为例子,讲述了三种实现HTML5动画的方式,思路清晰,动画不仅仅是canvas,还有css3和javascript.通过合理的选择,来实现最优的实现。P... @前端开发博客';var share_pic = '';var share_url = 'http://caibaojian.com/3-html5-animations.html';var wkey = '3586943907';var qkey = '101187318';window._bd_share_main = false;window._bd_share_config = { common : { bdText : share_excerpt,bdDesc : share_excerpt,bdUrl : share_url, bdPic : share_pic, bdSnsKey : {'tsina':wkey, 'tqq':qkey,'qzone':qkey} }, share : [{ 'bdStyle' : 1, 'bdSize' : 24 }] };</script></div><div class="btn-group vote-group" data-votes-up="6" data-votes-down="0" data-vote-id="5039" data-vote-type="post" itemscope="" itemtype="http://data-vocabulary.org/Review-aggregate"> <span href="javascript:void(0)" class="btn btn-zs show-zs">¥ 打赏</span> <a href="javascript:;" class="btn btn-default up"><span class="glyphicon glyphicon-thumbs-up"></span> 赞(<span class="votes">6</span>)<div class="hide" itemprop="rating" itemscope="" itemtype="http://data-vocabulary.org/Rating"><span itemprop="average">5</span><span itemprop="votes">6</span><span itemprop="count">0</span></div></a> <a href="javascript:;" class="btn btn-default down"><span class="glyphicon glyphicon-thumbs-down"></span></a></div></div><div class="content-box-inner" id="weiboshow" itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization"> <script>window.onload = function(){ //document.getElementById("weiboshow").innerHTML = '<iframe width="100%" height="200" class="share_self" frameborder="0" scrolling="no" src="http://widget.weibo.com/weiboshow/index.php?language=&width=0&height=220&fansRow=2&ptype=1&speed=0&skin=1&isTitle=0&noborder=1&isWeibo=0&isFans=1&uid=1748018491&verifier=5089da68&dpc=1"></iframe>'; }</script> </div><div class="relatedposts"><h3>相关文章</h3><ul class="related_posts inline-ul"><li class=""> <a rel="bookmark" href="http://caibaojian.com/canvas-circular.html" title="canvas绘制旋转的圆环百分比进度条">canvas绘制旋转的圆环百分比进度条</a><span class="entry-meta"> 9,432Views</span></li><li class=""> <a rel="bookmark" href="http://caibaojian.com/modernizr-js.html" title="Modernizr.js:为HTML5和CSS3而生!">Modernizr.js:为HTML5和CSS3而生!</a><span class="entry-meta"> 24,990Views</span></li><li class=""> <a rel="bookmark" href="http://caibaojian.com/the-best-webfrontend.html" title="为什么整个互联网行业都缺前端工程师?">为什么整个互联网行业都缺前端工程师?</a><span class="entry-meta"> 4,923Views</span></li><li class=""> <a rel="bookmark" href="http://caibaojian.com/learn-jquery-plugin-tutorial.html" title="开始学习并将深入学习jQuery插件制作">开始学习并将深入学习jQuery插件制作</a><span class="entry-meta"> 1,716Views</span></li><li class=""> <a rel="bookmark" href="http://caibaojian.com/js-lazyload.html" title="jQuery图片懒加载代码">jQuery图片懒加载代码</a><span class="entry-meta"> 1,681Views</span></li><li class=""> <a rel="bookmark" href="http://caibaojian.com/css-equal-layout.html" title="CSS自适应布局等分比例实践">CSS自适应布局等分比例实践</a><span class="entry-meta"> 18,638Views</span></li><li class=""> <a rel="bookmark" href="http://caibaojian.com/towards-retina-web.html" title="【译】走向Retina Web">【译】走向Retina Web</a><span class="entry-meta"> 1,417Views</span></li><li class=""> <a rel="bookmark" href="http://caibaojian.com/jquery-drag.html" title="jquery拖动代码">jquery拖动代码</a><span class="entry-meta"> 1,627Views</span></li></ul></div></article> 

原文:http://blog.csdn.net/yanghua_kobe/article/details/7226816

    原文作者:-jjjiong
    原文地址: https://blog.csdn.net/sinat_32434539/article/details/77893353
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞