天天看点

如何使用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>