1. 程式人生 > 實用技巧 >JavaScript動畫例項:炸開的小球

JavaScript動畫例項:炸開的小球

1.炸開的小球

定義一個小球物件類Ball,它有6個屬性:圓心座標(x,y)、小球半徑radius、填充顏色color、圓心座標水平方向的變化量speedX、圓心座標垂直方向的變化量speedY。

Ball類定義2個方法:繪製小球的方法draw()和小球位置發生變化的方法update()。

定義一個數組var balls = [];儲存小球物件。滑鼠單擊畫布,向陣列中隨機新增5~14個小球物件元素,當某個小球運動超出畫布範圍時,從陣列中刪除該小球物件元素。

編寫如下的HTML程式碼。

<html>
<head>
<title>炸開的小球</title>
</head>
<body>
<canvas id = "myCanvas" width="500" height="400" style="border:3px double #996633;"></canvas>
<script>
   var
canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); function Ball(x,y) { this.x = x; this.y = y; this.radius = Math.random()*15 + 10; this.color = "rgba("+Math.floor(Math.random()*256)+"," +Math.floor(Math.random()*256)+"," +Math.floor(Math.random()*256)+",0.8)";
var angle = Math.random() * 2 * Math.PI; this.speedX = Math.sin(angle) *(2+Math.random()*6); this.speedY = Math.cos(angle) *(2+Math.random()*6); } Ball.prototype.update = function(index) { this.x += this.speedX; this.y += this.speedY; if (this.x<0 || this
.x>=canvas.width || this.y<=0 || this.y>=canvas.height) { balls.splice(index,1); } } Ball.prototype.draw = function() { ctx.beginPath(); ctx.arc(this.x,this.y,this.radius,0,2*Math.PI); ctx.fillStyle = this.color; ctx.closePath(); ctx.fill(); } var balls = []; canvas.addEventListener('click', function(){ var x = event.pageX - canvas.getBoundingClientRect().left; var y = event.pageY - canvas.getBoundingClientRect().top; for (var i = 0; i < Math.floor(Math.random()*10+5); i++) { balls.push(new Ball(x,y)); } }); function go() { ctx.clearRect(0,0,500,400); for(var i = balls.length-1; i>=0 ;i--) { balls[i].draw(); balls[i].update(i); } requestAnimationFrame(go); } go(); </script> </body> </html>

在瀏覽器中開啟包含這段HTML程式碼的html檔案,可以看到在畫布中呈現出如圖1所示的動畫效果。

圖1 炸開的小球

2.按顏色消除小球

定義一個小球物件類Ball,它有6個屬性:圓心座標(x,y)、小球半徑radius、填充顏色color、圓心座標水平方向的變化量speedX、圓心座標垂直方向的變化量speedY。

Ball類定義1個方法:小球在畫布中移動的方法move()。小球移動過程中,碰到畫布的上下左右邊界後會反彈,反彈後繼續移動。

定義一個數組var balls = [];儲存小球物件,並向陣列中新增50個小球物件元素。

先編寫如下的HTML程式碼。

<!DOCTYPE html>
<html>
<head>
<title>彩色小球碰撞運動</title>
</head>
<body>
<canvas id="myCanvas" width="500" height="400" style="border:3px double #996633;">
</canvas>
<script type="text/javascript">
   var canvas=document.getElementById('myCanvas');
   ctx= canvas.getContext('2d');
   var colors = ["#0099CC","#33B5E5","#669900","#9933CC","#99CC00","#AA66CC","#CC0000","#FF4444","#FF8800", "#FFBB33"];
   function Ball()
   {
      this.x=Math.random()*(canvas.width-60)+30;
      this.y=Math.random()*(canvas.height-60)+30;
      this.radius=Math.random()*20+10;
      this.color=Math.floor(Math.random() * colors.length);
      this.speedX=Math.random()*10+1;
      this.speedY=Math.random()*10+1;
   }
   Ball.prototype.move=function()
   {
      ctx.beginPath();
      this.x += this.speedX;
      if (this.x>=canvas.width-this.radius || this.x<=this.radius) 
      {
          this.speedX*=-1;    
      }
      this.y+= this.speedY;
      if (this.y>=canvas.height-this.radius || this.y<=this.radius) 
      {
          this.speedY*=-1;    
      }
      ctx.fillStyle=colors[this.color];
      ctx.arc(this.x,this.y,this.radius,0,Math.PI*2);
      ctx.fill();
   }
   var balls=[];
   for (var i=0;i<50;i++)
   {
      balls[i]=new Ball();
   }
   function anim()
   {
      ctx.clearRect(0,0,canvas.width,canvas.height)
      for (var i=0;i<50;i++)
      {
          balls[i].move();
       }
      requestAnimationFrame(anim);     
   }
   anim();
</script>
</body>
</html>

在瀏覽器中開啟包含這段HTML程式碼的html檔案,可以看到在畫布中呈現出如圖2所示的動畫效果。

圖2 運動的彩色小球

在圖2效果的基礎上,新增互動式效果。可以在畫布的下方通過表格的方式佈置10個顏色塊,滑鼠單擊某個顏色塊,畫布中對應色塊填充的小球消失(從balls陣列中刪除對應的物件元素);若畫布中沒有對應色塊填充的小球,則顯示提示資訊“無對應色塊小球,無效單擊!”。

編寫的HTML檔案內容如下。

<!DOCTYPE html>
<html>
<head>
<title>按顏色消除彩色小球</title>
<style>
  .num
  {
     padding: 18px 0;
     border: 1px solid ;
     cursor: pointer;
  }
  #mess
  {
     border: 1px solid #FF6600;
     background-color: #FFFFCC;
     font-weight: bold;
     padding: 2px 5px;
     color: #FF6600;
  }
</style>
</head>
<body>
<canvas id="myCanvas" width="500" height="400" style="border:3px double #996633;">
</canvas><br/>
<table cellpadding="0" cellspacing="10">
<tbody><tr height="40">
<td bgcolor="#0099CC" width="40"><div id="c0" class="num" onclick="check(this);"></div></td>
<td bgcolor="#33B5E5" width="40"><div id="c1" class="num" onclick="check(this);"></div></td>
<td bgcolor="#669900" width="40"><div id="c2" class="num" onclick="check(this);"></div></td>
<td bgcolor="#9933CC" width="40"><div id="c3" class="num" onclick="check(this);"></div></td>
<td bgcolor="#99CC00" width="40"><div id="c4" class="num" onclick="check(this);"></div></td>
<td bgcolor="#AA66CC" width="40"><div id="c5" class="num" onclick="check(this);"></div></td>
<td bgcolor="#CC0000" width="40"><div id="c6" class="num" onclick="check(this);"></div></td>
<td bgcolor="#FF4444" width="40"><div id="c7" class="num" onclick="check(this);"></div></td>
<td bgcolor="#FF8800" width="40"><div id="c8" class="num" onclick="check(this);"></div></td>
<td bgcolor="#FFBB33" width="40"><div id="c9" class="num" onclick="check(this);"></div></td>
</tr>
</tbody>
</table><br/>
資訊: <span id="mess">&nbsp;</span>
<script type="text/javascript">
   var canvas=document.getElementById('myCanvas');
   ctx= canvas.getContext('2d');
   var colors = ["#0099CC","#33B5E5","#669900","#9933CC","#99CC00","#AA66CC","#CC0000","#FF4444","#FF8800", "#FFBB33"];
   function Ball()
   {
      this.x=Math.random()*(canvas.width-60)+30;
      this.y=Math.random()*(canvas.height-60)+30;
      this.radius=Math.random()*20+10;
      this.color=Math.floor(Math.random() * colors.length);
      this.speedX=Math.random()*10+1;
      this.speedY=Math.random()*10+1;
   }
   Ball.prototype.move=function()
   {
      ctx.beginPath();
      this.x += this.speedX;
      if (this.x>=canvas.width-this.radius || this.x<=this.radius) 
      {
          this.speedX*=-1;    
      }
      this.y+= this.speedY;
      if (this.y>=canvas.height-this.radius || this.y<=this.radius) 
      {
          this.speedY*=-1;    
      }
      ctx.fillStyle=colors[this.color];
      ctx.arc(this.x,this.y,this.radius,0,Math.PI*2);
      ctx.fill();
   }
   function check(d)
   {
       var cnt=0;
       var index= parseInt(d.id.charAt(1));
           for(var i = balls.length-1; i>=0 ;i--)
        {
            if (balls[i].color==index) 
            {
                balls.splice(i,1);
                cnt++;
            }
    }
        if (cnt==0)
            document.getElementById("mess").innerHTML ="無對應色塊小球,無效單擊";
        else
            document.getElementById("mess").innerHTML ="消除了"+cnt+"個小球。";
   }
   var balls=[];
   for (var i=0;i<50;i++)
   {
      balls[i]=new Ball();
   }
   function anim()
   {
      ctx.clearRect(0,0,canvas.width,canvas.height)
      for (var i=0;i<balls.length;i++)
      {
          balls[i].move();
       }
      requestAnimationFrame(anim);     
   }
   anim();
</script>
</body>
</html>
View Code

在瀏覽器中開啟包含這段HTML程式碼的html檔案,可以看到在畫布中呈現出如圖3所示的互動式動畫效果。

圖3 按指定顏色消除運動的小球