天天看點

如何使用canvas實作多個随機圓運動

此段代碼使用canvas畫布實作多個圓形自上向下滑落,圓的大小及顔色随機,背景圖檔可根據自己的喜好更換,隻需将大小與畫布大小統一即可。

文章下附有效果圖

   <body>  

<canvasid="canvas"width="493px"height="332px"></canvas>

<scripttype="text/javascript">

var 
  canvas
  =
  document
  .
  getElementById
  (
  "canvas"
  );//擷取<canvas>元素
 
 	
  var 
  context
  =
  canvas
  .
  getContext
  (
  "2d"
  );//建立畫布對象
 
 	
  //建立構造函數Circle
 
 	
  function 
  Circle
  (){
 
 	  
  this
  .
  x
  =
  Math
  .
  random
  ()
  *
  canvas
  .
  width
  ;
  //在畫布内随機生成x值
 
           
  //随機生成三原色
 
 	  
  this
  .
  r1 
  = 
  Math
  .
  floor
  (
  Math
  .
  random
  ()
  *
  256
  );
 
 	  
  this
  .
  g 
  = 
  Math
  .
  floor
  (
  Math
  .
  random
  ()
  *
  256
  );
 
 	  
  this
  .
  b 
  = 
  Math
  .
  floor
  (
  Math
  .
  random
  ()
  *
  256
  );
 
 	  
  this
  .
  y
  =-
  10
  ;
 
 	  
  this
  .
  r
  =
  Math
  .
  random
  ()
  *
  14
  ;
  //随機半徑r
 
 	  
  // 繪制圓形的方法
 
 	  
  this
  .
  paint
  =
  function
  (){
 
 	    
  context
  .
  beginPath
  ();
 
 		
  context
  .
  globalAlpha 
  = 
  0.7
  ;
  //設定透明度
 
 		
  context
  .
  strokeStyle
  =
  "rgb("
  +
  this
  .
  r1
  +
  ","
  +
  this
  .
  g
  +
  ","
  +
  this
  .
  b
  +
  ")"
  ;
  //将随機生成的三原色設為圓形的顔色
 
 		
  context
  .
  arc
  (
  this
  .
  x
  ,
  this
  .
  y
  ,
  this
  .
  r
  ,
  0
  ,
  Math
  .
  PI
  *
  2
  );
  //繪制圓形
 
 		
  context
  .
  stroke
  ();
 
 	  
  }
 
 	  
  // 控制圓形移動的方法
 
 	  
  this
  .
  step
  =
  function
  (){
 
 	    
  this
  .
  y
  ++
 
 	  
  }
 
 	
  }
 
 	
  var 
  circles
  =
  [];
 
 	
  //  建立圓形對象
 
 	
  function 
  createCircles
  (){
 
 	  
  var 
  circle
  =
  new 
  Circle
  ();
  //調用構造函數
 
 	  
  circles
  [
  circles
  .
  length
  ]
  =
  circle
  ;
  //将繪制的圖形追加到數組
 
 	
  }
 
 	
  // 繪制所有圓形
 
 	
  function 
  paintCircles
  (){
 
 	  
  for
  (
  var 
  i
  =
  0
  ;
  i
  <
  circles
  .
  length
  ;
  i
  ++
  ){
 
 		
  circles
  [
  i
  ].
  paint
  ();
  //周遊數組,将數組内的圖形繪制
 
 	  
  }
 
 	
  }
 
 	
  //  控制所有圓形運動
 
 	
  function 
  stepCircles
  (){
 
 	   
  for
  (
  var 
  i
  =
  0
  ;
  i
  <
  circles
  .
  length
  ;
  i
  ++
  ){
 
 	      
  circles
  [
  i
  ].
  step
  ();
 
 	   
  }
 
 	
  }
 
      
  //繪制一張圖檔
 
     
  var 
  myimg
  =
  new 
  Image
  ();
 
 	
  myimg
  .
  src
  =
  "bgg.jpg"
  ;
 
 
  

 
 	
  var 
  time
  =
  0
  ;
 
 	
  //設定定時器
 
 	
  setInterval
  (
  function
  (){
 
 	  
  context
  .
  drawImage
  (
  myimg
  ,
  0
  ,
  0
  );
 
 	  
  time
  ++
  ;
  //控制繪制時間
 
 	  
  if
  (
  time
  %
  20
  ==
  0
  ){
 
 	    
  createCircles
  ();
 
 	  
  }
 
 	  
  paintCircles
  ();
 
 	  
  stepCircles
  ();
 
 	
  },
  50
  );
 
   
  </script>
 
 
   
  </body>