1. 程式人生 > 程式設計 >原生js canvas實現滑鼠跟隨效果

原生js canvas實現滑鼠跟隨效果

本文例項為大家分享了canvas實現滑鼠跟隨效果的具體程式碼,供大家參考,具體內容如下

效果展示:

原生js canvas實現滑鼠跟隨效果

原始碼展示:

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>canvas滑鼠跟隨效果(原生js實現)</title>
  <script src="http://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script>
  <style>
    * {
      margin:0;
      padding:0;
    }
    body {
      overflow:hidden;
    }
    #myCanvas {
      background-color:#000;
    }
  </style>
</head>
<body>
<canvas id="myCanvas"></canvas>
 
<script>
  var myCanvas = document.getElementById('myCanvas');
  var ctx = myCanvas.getContext("2d");
  var starlist = [];
 
  function init() {
    // 設定canvas區域的範圍為整個頁面
    myCanvas.width = window.innerWidth;
    myCanvas.height = window.innerHeight;
  };
  init();
  // 監聽螢幕大小改變 重新為canvas大小賦值
  window.onresize = init;
 
  // 當滑鼠移動時 將滑鼠座標傳入建構函式 同時建立一個物件
  myCanvas.addEventListener('mousemove',function(e) {
    // 將物件push到陣列中,畫出來的彩色小點可以看作每一個物件中記錄著資訊 然後存在陣列中
    starlist.push(new Star(e.offsetX,e.offsetY));
  });
 
  // 隨機數函式
  function random(min,max) {
    // 設定生成隨機數公式
    return Math.floor((max - min) * Math.random() + min);
  };
 
 
  // 建構函式
  function Star(x,y) {
    // 將座標存在每一個點的物件中
    this.x = x;
    this.y = y;
    // 設定隨機偏移量
    this.vx = (Math.random() - 0.5) * 3;
    this.vy = (Math.random() - 0.5) * 3;
    this.color = 'rgb(' + random(0,256) + ',' + random(0,256) + ')';
    // 初始透明度
    this.a = 1;
    // 開始畫
    this.draw();
  }
 
  // 再star物件原型上封裝方法
  Star.prototype = {
    // canvas根據陣列中存在的每一個物件的小點資訊開始畫
    draw: function() {
      ctx.beginPath();
      ctx.fillStyle = this.color;
      // 影象覆蓋 顯示方式 lighter 會將覆蓋部分的顏色重疊顯示出來
      ctx.globalCompositeOperation = 'lighter'
      ctx.globalAlpha = this.a;
      ctx.arc(this.x,this.y,30,Math.PI * 2,false);
      ctx.fill();
      this.updata();
    },updata: function() {
      // 根據偏移量更新每一個小點的位置
      this.x += this.vx;
      this.y += this.vy;
      // 透明度越來越小
      this.a *= 0.98;
    }
  }
  // 渲染
  function render() {
    // 每一次根據改變後陣列中的元素進行畫圓圈 把原來的內容區域清除掉
    ctx.clearRect(0,myCanvas.width,myCanvas.height)
 
    // 根據存在陣列中的每一位物件中的資訊畫圓
    starlist.forEach(function(ele,i) {
      ele.draw();
      // 如果陣列中存在透明度小的物件 ,給他去掉 效果展示逐漸消失
      if (ele.a < 0.05) {
        starlist.splice(i,1);
      }
    });
    requestAnimationFrame(render);
  }
  render();
</script>
<pre style="color:red">
 感: 最近貢獻一下我在教學中的小案例可以能給你一些幫助,希望繼續關注我的部落格
                                        --王
</pre> 
 
</body>
</html>

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。