canvas 雪花連線

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style>
   *{padding:0; margin: 0;}
#canvas{display: block; background-color: black;}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
  <script>
  //1.獲取屏幕寬高,
  //2.定義圓函數,將它放置數量裏
  //3.存放隨機變量值 ,創建attr 存放隨機變量值;
  //4.重新繪製圓.然後判斷寬高,速度隨機;
  //5.定義多一個for循環 j 循環判定距離    //距離  x座標減去另一個x座標的平方 + y座標減去另一個y座標的平方 =根號  然後連線
  //6.用數組存放鼠標位置,在for循環第一層判斷是否有鼠標進入,如果有就產生一個原點,並判斷距離,




  var canvas =document.getElementById("canvas");
  var cxt=canvas.getContext("2d");
  canvas.width=window.innerWidth;
  canvas.height=window.innerHeight;
  var w=canvas.width;
  var h=canvas.height;
  var mun=250;
  var attr=[];
  var move={};
  document.οnmοusemοve=function(e){
  move.x=e.pageX;
  move.y=e.pageY;
  };
 
  for(var i=0; i<mun; i++)
  {
  attr[i]={ x:Math.random()*w, y:Math.random()*h, Cw:Math.random()*3-0.5, Cx:Math.random()*3-0.5 };
      Creen(attr[i].x,attr[i].y)
  }
 
  function Creen(x,y){
   cxt.save();
   cxt.beginPath();
             cxt.arc( x,   y,  10, 0, Math.PI * 2, true);
             cxt.closePath();
            cxt.fillStyle = 'white';
             cxt.fill();
  cxt.restore();
 
  }
  function anew(){
  cxt.save();
  cxt.beginPath();
  cxt.clearRect(0,0,w,h);
   
    for(var i=0; i<mun; i++)
  {
         attr[i].x+=attr[i].Cw;
          attr[i].y+=attr[i].Cx;
     Creen(attr[i].x,attr[i].y);
    if(attr[i].x>=w||attr[i].x<=0) attr[i].Cw=-attr[i].Cw;
    if(attr[i].y>=w||attr[i].y<=0) attr[i].Cx=-attr[i].Cx;
        for(var j=0; j<mun; j++)
        {
        if((attr[i].x-attr[j].x)*(attr[i].x-attr[j].x)+(attr[i].y-attr[j].y)*(attr[i].y-attr[j].y)<=50*50)
        {
        stok(attr[i].x,attr[i].y,attr[j].x,attr[j].y,false)
        }
        }
        if(move)
        {
        if((attr[i].x-move.x)*(attr[i].x-move.x)+(attr[i].y-move.y)*(attr[i].y-move.y)<=80*80)
        {
        stok(attr[i].x,attr[i].y,move.x,move.y,true)
       
        }
       
        }
        
  }
 
  function stok(x1,y1,x2,y2,is){
  if(is)
  {
   var grad  = cxt.createLinearGradient(0,0, 0,140);
  grad.addColorStop(0,'rgb(192, 80, 77)');  
          
            grad.addColorStop(1,'rgb(128, 100, 162)');   
           cxt.lineWidth = 1; 
             cxt.strokeStyle=grad;
           
  }
  else{
  cxt.strokeStyle="white";
  }
 
  cxt.save();
           
  cxt.moveTo(x1, y1);
            cxt.lineTo(x2,y2);
           cxt.lineWidth="3";
  cxt.stroke();
  cxt.restore();
  }
       
  cxt.restore();
  requestAnimationFrame(anew)
  }
  requestAnimationFrame(anew)
   
 
 
 
 
  </script>






</body>

</html>




發佈了26 篇原創文章 · 獲贊 3 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章