DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> HTML基礎知識 >> HTML5詳解
用 HTML5 打造動畫(一):Canvas 基礎位移實作
編輯:HTML5詳解     

HTML5 的 Canvas 為網頁動畫帶來了全新的可能。本系列將從最基礎的方塊位移開始,一步步帶你走進 Canvas 動畫的世界。第一篇,我們先來看一個最經典的上下往返移動方塊範例。

核心思路很簡單:透過 setInterval 建立計時器,不斷清空畫布並重新繪製方塊,同時根據邊界偵測來反轉移動方向,就能讓方塊持續來回彈跳。

<canvas id="canvas1" width="250" height="300" style="background-color:black">
  你的瀏覽器不支援 Canvas 標籤,請使用 Chrome 瀏覽器或者 Firefox 瀏覽器
</canvas><br/>
  幀數:<input  id="txt1" type="text" value="25"/><br/>
  每次移動距離:<input type="text" id="txt2" value="10"/><br/>
<input type="button" value="開始" onclick="move_box()"/>
<input type="button" value="暫停" onclick="stop()"/>
<script type="text/Javascript">
   //定時器
   var interval=null;
   //停止動畫
   function stop(){
     clearInterval(interval);
   }
   //===================================================================
   //基本動畫
   //====================================================================
   function move_box(){
     //停止動畫
     stop();
     //移動速度
     var delta=parseInt(document.getElementById('txt1').value);
     //每秒繪制多少次
     var fps=parseInt(document.getElementById('txt2').value);
     //畫布對象
     var canvas=document.getElementById("canvas1")
     //獲取上下文對象
     var ctx = canvas.getContext("2d");
     //設置顏色
     ctx.fillStyle="red";
     //方塊的初始位置
     var x=100;var y=50;
     //方塊的長度和寬度
     var w=30;var h=30;
     //開始動畫
     interval = setInterval(function(){
       //改變 y 坐標
       yy=y+delta;
       //上邊緣檢測
       if(y<0){
         y=0;
         delta=-delta;
       }
       //下邊緣檢測
       if((y+h)>canvas.getAttribute("height")){
         y=canvas.getAttribute("height")-h;
         delta=-delta;
       }
       //清空畫布
       ctx.clearRect(0,0,canvas.getAttribute("width"),canvas.getAttribute("height"));
       //保存狀態
       ctx.save();
       //移動坐標
       ctx.translate(x,y);
       //重新繪制
       ctx.fillRect(0,0,w,h);
       //恢復狀態
       ctx.restore();
     },1000/fps);
   }
</script>

源碼下載:donghua1.rar

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved