js+canvas實現代碼雨效果

本文實例為大傢分享瞭js+canvas代碼雨效果的具體代碼,供大傢參考,具體內容如下

代碼:

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8" />
  <title></title>
  <style type="text/css">
   *{
    margin: 0px;
    padding: 0px;
   }
   html,body{
    height: 100%;
    width: 100%;
   }
   #canvas{
    display: block;
   }
  </style>
 </head>
 <body>
  <canvas id="canvas"></canvas>
  <script type="text/javascript">
   var canvas = document.getElementById('canvas')
   var c= canvas.getContext('2d')
   var cw = canvas.width = window.innerWidth
   var ch = canvas.height = window.innerHeight 
   
   var str = [1,2,3,4,5,6,7,8,9,0,'q','w','e','r','t','y','u','i','a','c','d','f','g','h','j','l']
   var init = function(){
    this.x = Math.random()*cw
    this.y = 0
    this.content1 =Math.random()*15 
    this.speed = Math.random()*5+20
    this.add = function(){
     this.y+=this.speed
    }
    this.reset1 = function(){
     this.x= Math.random()*cw
     this.y = 0
    }
   }
   //定義一個隨機色
   var gl = c.createLinearGradient(0, 0, cw, ch);
       gl.addColorStop(0, 'red');
       
       gl.addColorStop(.5, 'yellow');
       
       gl.addColorStop(1, 'cyan');
   
   var arr=[]
   for(var i=0;i<20;i++){
    arr.push(new init())
   }
   setInterval(function(){
    
    c.fillStyle = 'rgba(0,0,0,0.05)'
    c.fillRect(0,0,cw,ch)
    //上面的兩句是給一個背景,放在計時器裡面是為瞭每運行一次,就重新繪畫一次
    //用來清空好畫佈
    //1,yong rgba()來表示顏色是為瞭給一個透明度,新畫上去的畫佈沒有完全覆蓋
    //以前的畫佈,所以有個漸變的效果
    
    for(var i=0;i<arr.length;i++){
     c.fillStyle = gl
     c.font = '30px 微軟雅黑'
     
     c.fillText(str[i],arr[i].x,arr[i].y)
     
     //讓他落到底部再回來
     if(arr[i].y>ch-20){
      arr[i].reset1()
     }
     arr[i].add()
    }
    
    
    //
   },1000/60)
  </script>
 </body>
</html>

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: