溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

HTML如何實(shí)現(xiàn)動畫

發(fā)布時(shí)間:2022-02-22 14:10:29 來源:億速云 閱讀:133 作者:小新 欄目:開發(fā)技術(shù)

小編給大家分享一下HTML如何實(shí)現(xiàn)動畫,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

方法一: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,          //當(dāng)前速率 
            rate=1,         //當(dāng)前播放速度 
            ani,            //當(dāng)前動畫循環(huán) 
            c,              //畫圖(Canvas Context) 
            w,              //汽車[隱藏的](Canvas Context) 
            grassHeight=130,        //背景高度 
            carAlpha=0,         //輪胎的旋轉(zhuǎn)角度 
            carX=-400,          //x軸方向上汽車的位置(將被改變) 
            carY=300,           //y軸方向上汽車的位置(將保持為常量) 
            carWidth=400,       //汽車的寬度 
            carHeight=130,      //汽車的高度 
            tiresDelta=15,      //從一個(gè)輪胎到最接近的汽車底盤的距離 
            axisDelta=20,       //汽車底部底盤的軸與輪胎的距離 
            radius=60;          //輪胎的半徑

我們在實(shí)例化汽車的時(shí)候 canvas 會被隱藏,那么我們做了下面這個(gè)步驟:

(function(){ 
           var car=document.createElement('canvas');    //創(chuàng)建元素 
           car.height=carHeight+axisDelta+radius;   //設(shè)置高度 
           car.width=carWidth;              //設(shè)置寬度 
           w=car.getContext('2d'); 
        })();

之后我們進(jìn)行點(diǎn)擊Play,在通過指定重復(fù)執(zhí)行“畫汽車”操作,來模擬“幀播放”功能代碼如下所示:

function play(s){               //參數(shù)s是一個(gè)button 
           if(ani){                 //如果ani不為null,則代表我們當(dāng)前已經(jīng)有了一個(gè)動畫 
              clearInterval(ani);           //所以我們需要清除它(停止動畫) 
              ani=null; 
              s.innerHTML='Play';           //重命名該按鈕為“播放” 
           }else{ 
              ani=setInterval(drawCanvas,40);       //我們將設(shè)置動畫為25fps[幀每秒],40/1000,即為二十五分之一 
             s.innerHTML='Pause';          //重命名該按鈕為“暫停” 
           } 
        }

加速,減速,通過以下方法,改變移動距離的大小來實(shí)現(xiàn):

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(); 
        }

主調(diào)方法:

function drawCanvas(){ 
           c.clearRect(0,0,c.canvas.width, c.canvas.height);    //清除Canvas(已顯示的),避免產(chǎn)生錯(cuò)誤 
           c.save();                        //保存當(dāng)前坐標(biāo)值以及狀態(tài),對應(yīng)的類似“push”操作    drawGrass();                     //畫背景
       c.translate(carX,0);                 //移動起點(diǎn)坐標(biāo)
       drawCar();                       //畫汽車(隱藏的canvas)
       c.drawImage(w.canvas,0,carY);            //畫最終顯示的汽車
       c.restore();                     //恢復(fù)Canvas的狀態(tài),對應(yīng)的是類似“pop”操作
       carX+=dx;                        //重置汽車在X軸方向的位置,以模擬向前走
       carAlpha+=dx/radius;                 //按比例增加輪胎角度
       if(carX&gt;c.canvas.width){              //設(shè)置某些定期的邊界條件
          carX=-carWidth-10;                //也可以將速度反向?yàn)閐x*=-1;
       }

畫背景:

function drawGrass(){
       //創(chuàng)建線性漸變,前兩個(gè)參數(shù)為漸變開始點(diǎn)坐標(biāo),后兩個(gè)為漸變結(jié)束點(diǎn)坐標(biāo)
       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';                 //設(shè)置邊框色
       w.lineWidth=2;                       //設(shè)置邊框的寬度,單位為像素
       w.fillStyle='#FF9900';                   //設(shè)置填充色
       w.beginPath();                       //開始繪制新路徑
       w.rect(0,0,carWidth,carHeight);              //繪制一個(gè)矩形
       w.stroke();                          //畫邊框
       w.fill();                            //填充背景
       w.closePath();                       //關(guān)閉繪制的新路徑
       drawTire(tiresDelta+radius,carHeight+axisDelta);     //我們開始畫第一個(gè)輪子
       drawTire(carWidth-tiresDelta-radius,carHeight+axisDelta);    //同樣的,第二個(gè)

    }

畫輪胎:

unction 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();

    }

由于原理簡單,并且代碼中作了詳細(xì)注釋,這里就不一一講解!

方法二:CSS3

你將看到我們未通過一句JS代碼就完全實(shí)現(xiàn)了和上面一樣的動畫效果:

HTML代碼:

<html>
<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; 
     }

定義車身與輪胎轉(zhuǎn)到的動畫(你會看到基本每一個(gè)動畫都有四個(gè)版本的定義:原生版本/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" > @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" > #container
 {
    position:relative;
    width:100%;
    height:600px;
    overflow:hidden;        /*這個(gè)很重要*/
 }

 #car
 {
    position:absolute;      /*汽車在容器中采用絕對定位*/
    width:400px;
    height:210px;       /*汽車的總高度,包括輪胎和底盤*/
    z-index:1;          /*讓汽車在背景的上方*/
    top:300px;          /*距頂端的距離(y軸)*/
    left:50px;          /*距左側(cè)的距離(x軸)*/

    /*以下內(nèi)容賦予該元素預(yù)先定義的動畫及相關(guān)屬性*/
    -webkit-animation-name:carAnimation;        /*名稱*/
    -webkit-animation-duration:10s;         /*持續(xù)時(shí)間*/
    -webkit-animation-iteration-count:infinite;     /*迭代次數(shù)-無限次*/
    -webkit-animation-timing-function:linear;       /*播放動畫時(shí)從頭到尾都以相同的速度*/

    -moz-animation-name:carAnimation;       /*名稱*/
    -moz-animation-duration:10s;            /*持續(xù)時(shí)間*/
    -moz-animation-iteration-count:infinite;        /*迭代次數(shù)-無限次*/
    -moz-animation-timing-function:linear;      /*播放動畫時(shí)從頭到尾都以相同的速度*/

    -ms-animation-name:carAnimation;        /*名稱*/
    -ms-animation-duration:10s;         /*持續(xù)時(shí)間*/
    -ms-animation-iteration-count:infinite;     /*迭代次數(shù)-無限次*/
    -ms-animation-timing-function:linear;       /*播放動畫時(shí)從頭到尾都以相同的速度*/

    animation-name:carAnimation;        /*名稱*/
    animation-duration:10s;         /*持續(xù)時(shí)間*/
    animation-iteration-count:infinite;     /*迭代次數(shù)-無限次*/
    animation-timing-function:linear;       /*播放動畫時(shí)從頭到尾都以相同的速度*/
 }/*車身*/
 #chassis
 {
    position:absolute;
    width:400px;
    height:130px;
    background:#FF9900;
    border: 2px solid #FF6600;
 }

 /*輪胎*/
 .tire
 {
    z-index:1;          /*同上,輪胎也應(yīng)置于背景的上方*/
    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;     /*設(shè)置右邊的輪胎距離邊緣的距離為20*/
 }

 #backtire
 {
    left:20px;      /*設(shè)置左邊的輪胎距離邊緣的距離為20*/
 }

 #grass
 {
    position:absolute;  /*背景絕對定位在容器中*/
    width:100%;
    height:130px;
    bottom:0;
    /*讓背景色線性漸變,bottom,表示漸變的起始處,第一個(gè)顏色值是漸變的起始值,第二個(gè)顏色值是終止值 */
    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

這是一個(gè)效果與兼容性俱佳的方式(特別對于IE9暫不支持CSS3而言)

HTML代碼(可以看到與CSS3中的HTML代碼并無不同):

<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;        /*這個(gè)很重要*/
 }

 #car
 {
    position:absolute;      /*汽車在容器中采用絕對定位*/
    width:400px;
    height:210px;       /*汽車的總高度,包括輪胎和底盤*/
    z-index:1;          /*讓汽車在背景的上方*/
    top:300px;          /*距頂端的距離(y軸)*/
    left:50px;          /*距左側(cè)的距離(x軸)*/
 }

  /*車身*/
 #chassis
 {
    position:absolute;
    width:400px;
    height:130px;
    background:#FF9900;
    border: 2px solid #FF6600;
 }

 /*輪胎*/
 .tire
 {
    z-index:1;          /*同上,輪胎也應(yīng)置于背景的上方*/
    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);  /*旋轉(zhuǎn)(單位:度)*/
    -ms-transform:rotate(0deg);
    -webkit-transform:rotate(0deg);
    -moz-transform:rotate(0deg);
 }

 #fronttire
 {
    right:20px;     /*設(shè)置右邊的輪胎距離邊緣的距離為20*/
 }

 #backtire
 {
    left:20px;      /*設(shè)置左邊的輪胎距離邊緣的距離為20*/
 }

 #grass
 {
    position:absolute;  /*背景絕對定位在容器中*/
    width:100%;
    height:130px;
    bottom:0;
    /*讓背景色線性漸變,bottom,表示漸變的起始處,第一個(gè)顏色值是漸變的起始值,第二個(gè)顏色值是終止值 */
    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;
 }

JS代碼:

首先引入在線API:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

實(shí)現(xiàn)動畫代碼(相當(dāng)簡潔):

  $(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={       /*設(shè)置我們的起始點(diǎn)*/
     left:-400
     };

     var animation={        /*該動畫由jQuery執(zhí)行*/
     left:1600      /*設(shè)置我們將移動到的最終位置*/
 };

     var rotate=function(){ /*該方法將被旋轉(zhuǎn)的輪子調(diào)用*/
     rot+=2;
     $('.tire').css(prefix,'rotate('+rot+'deg)');
 };

     var options={      /*將要被jQuery使用的參數(shù)*/
     easing:'linear',   /*指定速度,此處只是線性,即為勻速*/
     duration:10000,    /*指定動畫持續(xù)時(shí)間*/
     complete:function(){
        $('#car').css(origin).animate(animation,options);
     },
     step:rotate
 };

     options.complete();
  });

簡單講解:prefix首先識別出當(dāng)前是哪個(gè)定義被采用了(-o?-moz?-webkit?-ms?),然后定義了動畫的起點(diǎn)位置和終點(diǎn)位置。接著,定義了設(shè)置旋轉(zhuǎn)角度的函數(shù)(該函數(shù)將在在動畫的每一步(step)中執(zhí)行)。然后,定義了一個(gè)動畫,該定義方式導(dǎo)致了無限自循環(huán)調(diào)用!

以上是“HTML如何實(shí)現(xiàn)動畫”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI