欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

原生js canvas實現(xiàn)鼠標跟隨效果

 更新時間:2020年08月02日 10:55:12   作者:Mr.王征  
這篇文章主要為大家詳細介紹了原生js canvas實現(xiàn)鼠標跟隨效果,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下

本文實例為大家分享了canvas實現(xiàn)鼠標跟隨效果的具體代碼,供大家參考,具體內容如下

效果展示:

源碼展示:

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>canvas鼠標跟隨效果(原生js實現(xiàn))</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區(qū)域的范圍為整個頁面
    myCanvas.width = window.innerWidth;
    myCanvas.height = window.innerHeight;
  };
  init();
  // 監(jiān)聽屏幕大小改變 重新為canvas大小賦值
  window.onresize = init;
 
  // 當鼠標移動時 將鼠標坐標傳入構造函數(shù) 同時創(chuàng)建一個對象
  myCanvas.addEventListener('mousemove', function(e) {
    // 將對象push到數(shù)組中,畫出來的彩色小點可以看作每一個對象中記錄著信息 然后存在數(shù)組中
    starlist.push(new Star(e.offsetX, e.offsetY));
  });
 
  // 隨機數(shù)函數(shù)
  function random(min, max) {
    // 設置生成隨機數(shù)公式
    return Math.floor((max - min) * Math.random() + min);
  };
 
 
  // 構造函數(shù)
  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) + ',' + random(0, 256) + ')';
    // 初始透明度
    this.a = 1;
    // 開始畫
    this.draw();
  }
 
  // 再star對象原型上封裝方法
  Star.prototype = {
    // canvas根據數(shù)組中存在的每一個對象的小點信息開始畫
    draw: function() {
      ctx.beginPath();
      ctx.fillStyle = this.color;
      // 圖像覆蓋 顯示方式 lighter 會將覆蓋部分的顏色重疊顯示出來
      ctx.globalCompositeOperation = 'lighter'
      ctx.globalAlpha = this.a;
      ctx.arc(this.x, this.y, 30, 0, Math.PI * 2, false);
      ctx.fill();
      this.updata();
    },
    updata: function() {
      // 根據偏移量更新每一個小點的位置
      this.x += this.vx;
      this.y += this.vy;
      // 透明度越來越小
      this.a *= 0.98;
    }
  }
  // 渲染
  function render() {
    // 每一次根據改變后數(shù)組中的元素進行畫圓圈 把原來的內容區(qū)域清除掉
    ctx.clearRect(0, 0, myCanvas.width, myCanvas.height)
 
    // 根據存在數(shù)組中的每一位對象中的信息畫圓
    starlist.forEach(function(ele, i) {
      ele.draw();
      // 如果數(shù)組中存在透明度小的對象 ,給他去掉 效果展示逐漸消失
      if (ele.a < 0.05) {
        starlist.splice(i, 1);
      }
    });
    requestAnimationFrame(render);
  }
  render();
</script>
<pre style="color:red">
 感: 最近貢獻一下我在教學中的小案例可以能給你一些幫助 ,希望繼續(xù)關注我的博客
                                        --王
</pre> 
 
</body>
</html>

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

相關文章

最新評論