当前位置: 移动技术网 > IT编程>网页制作>Html5 > HTML5 实现小车动画效果(Canvas/CSS3/JQuery)

HTML5 实现小车动画效果(Canvas/CSS3/JQuery)

2018年11月04日  | 移动技术网IT编程  | 我要评论

欧嘉霓,www.38tv.cc,传说中的故乡之九尾狐

html5正在变得越来越流行。在这个移动设备日益增长的时代,对来自adobe的flash插件的改造需求也正在快速增长。因为就在最近,adobe宣布flash将不再支持移动设备。这意味着,adobe自身也认为对移动设备来讲html5是一项重要的技术。而桌面的改变也是迟早的事。
 
html的一大劣势就是对于多媒体技术支持的缺乏。在html中,你无法直接显示一个视频或在屏幕上绘画。在html5中,随着<video>与<canvas>元素的引进。这些元素给予开发者直接使用“纯粹的”html来实现多媒体技术的可能性——仅需要写一些javascript代码来配合html。在多媒体技术中,有一个基本的技术应该被支持——动画。在html5中,有不少方式能够实现该功能。
 
在这篇文章中,我仅将最新的<canvas>元素与即将到来的css3动画技术进行比较。其他的可能性包括dom元素或svg元素的创建和动画。这些可能性将不在本文中进行讨论。从开始就应该注意到canvas技术在当前发布的大部分主流都给予了支持,而css3动画仅在最新的firefox与chrome浏览器中才有实现的可能,下一个版本的ie也将提供对css3动画的支持。(所以本文中所有演示代码的效果,在win 7系统下当前最新版的chrome浏览器中都可实现,但在其他操作系统与其他浏览器中,并不一定能看到所有演示代码的效果)。
 
这里我选择了一个比较简单的动画:

\
 
ps:由于显卡、录制的帧间隔,以及可能你电脑处理器的原因,播放过程可能有些不太流畅或者失真!
分三种方式实现:
(1)   canvas元素结合js
(2)   纯粹的css3动画(暂不被所有主流浏览器支持,比如ie)
(3)   css3结合jquery实现
知道如何使用css3动画比知道如何使用<canvas>元素更重要:因为浏览器能够优化那些元素的性能(通常是他们的样式,比如css),而我们使用canvas自定义画出来的效果却不能被优化。原因又在于,浏览器使用的硬件主要取决于显卡的能力。目前,浏览器没有给予我们直接访问显卡的权力,比如,每一个绘画操作都不得不在浏览器中先调用某些函数。
 
让我们从canvas开始
html代码:
[html]
<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> 
      <p 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> 
      </p> 
   </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;          //轮胎的半径  www.2cto.com
 
为了实例化汽车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>c.canvas.width){              //设置某些定期的边界条件 
              carx=-carwidth-10;                //也可以将速度反向为dx*=-1; 
           } 
        } 
 
画背景:
 
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); 
            
        } 
 
画车身:
 
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);    //同样的,第二个 
            
        } 
 
画轮胎:
 
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(); 
 
        } 
由于原理简单,并且代码中作了详细注释,这里就不一一讲解!
 
该是css3出场了
你将看到我们未通过一句js代码就完全实现了和上面一样的动画效果:
html代码:
[html]
<html> 
   <head> 
      <meta charset="utf-8" /> 
      <title>animations in html5 using css3 animations</title> 
       </head> 
   <body> 
      <p id="container"> 
      <p id="car"> 
         <p id="chassis"></p> 
         <p id="backtire" class="tire"> 
         <p class="hr"></p> 
         <p class="vr"></p> 
         </p> 
         <p id="fronttire" class="tire"> 
         <p class="hr"></p> 
         <p class="vr"></p> 
         </p>    
      </p> 
      <p id="grass"></p> 
      </p> 
      <footer></footer> 
   </body> 
</html> 
 
css代码:
[css]
body 
 { 
    padding:0; 
    margin:0; 
 } 
 
定义车身与轮胎转到的动画(你会看到基本每一个动画都有四个版本的定义:原生版本/webkit【chrome|safari】/ms【为了向后兼容ie10】/moz【firefox】)
[css]
/*定义动画:从-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; } 
 } 
 
[css]
@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); } 
 } 
 
[css]
#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; 
 } 
 
jquery与css3合体
这是一个效果与兼容性俱佳的方式(特别对于ie9暂不支持css3而言)
html代码(可以看到与css3中的html代码并无不同):
[html]
<html> 
   <head> 
      <meta charset="utf-8" /> 
      <title>animations in html5 using css3 animations</title> 
       </head> 
   <body> 
      <p id="container"> 
      <p id="car"> 
         <p id="chassis"></p> 
         <p id="backtire" class="tire"> 
         <p class="hr"></p> 
         <p class="vr"></p> 
         </p> 
         <p id="fronttire" class="tire"> 
         <p class="hr"></p> 
         <p class="vr"></p> 
         </p>    
      </p> 
      <p id="grass"></p> 
      </p> 
      <footer></footer> 
   </body> 
</html>  
 
css:
[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; 
     } 
 
      </style> 
 
js代码:
首先引入在线api:
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> 
 
实现动画代码(相当简洁):
 
<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={       /*设置我们的起始点*/ 
         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(); 
      }); 
      </script> 
 
简单讲解:prefix首先识别出当前是哪个定义被采用了(-o?-moz?-webkit?-ms?),然后定义了动画的起点位置和终点位置。接着,定义了设置旋转角度的函数(该函数将在在动画的每一步(step)中执行)。然后,定义了一个动画,该定义方式导致了无限自循环调用!
 
本文,通过一个简单的动画实例,演示了html5下,实现动画的几种常见方式。

摘自 yanghua_kobe的专栏

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网