canvas 粒子动画_代码笔记

canvas 粒子动画

2025-06-24 09:28:37  浏览:36  作者:保利尼奥
<canvas width="1920" height="222" class="particles"></canvas> <script> $(function(){ var canvas = document.querySelector(&#39;c...
<canvas width="1920" height="222" class="particles"></canvas>

<script>
$(function(){
  var canvas = document.querySelector('canvas'),
      ctx = canvas.getContext('2d');
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  ctx.lineWidth = .3;

  var mousePosition = {
    x: 30 * canvas.width / 100,
    y: 30 * canvas.height / 100
  };

  var mouseActive = false; // 鼠标是否在canvas内

  var dots = {
    nb: 1000,
    array: []
  };

  function Dot(){
    this.x = Math.random() * canvas.width;
    this.y = Math.random() * canvas.height;

    this.vx = (-0.5 + Math.random()) * 0.2;
    this.vy = (-0.5 + Math.random()) * 0.2;

    this.radius = Math.random() * 2;

    this.color = {
      r: 0,
      g: 120,
      b: 255,
      style: 'rgba(0, 120, 255, 0.8)'
    };
  }

  Dot.prototype = {
    draw: function(){
      ctx.beginPath();
      ctx.fillStyle = this.color.style;
      ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
      ctx.fill();
    }
  };

  function createDots(){
    for(var i = 0; i < dots.nb; i++){
      dots.array.push(new Dot());
    }
  }

  function moveDots() {
    for(var i = 0; i < dots.nb; i++){
      var dot = dots.array[i];

      if(dot.y < 0 || dot.y > canvas.height){
        dot.vy = - dot.vy;
      }
      if(dot.x < 0 || dot.x > canvas.width){
        dot.vx = - dot.vx;
      }

      if(mouseActive){
        // 计算粒子与鼠标的向量差
        var dx = dot.x - mousePosition.x;
        var dy = dot.y - mousePosition.y;
        var dist = Math.sqrt(dx*dx + dy*dy) || 1; // 防止除0

        // 反方向推动力,距离越近,推动力越大,避免太大我们用缩放因子
        var force = 0.5 / dist; // 力大小,可调节

        // 将力分解成vx vy方向,叠加到当前速度上(反方向)
        dot.vx += (dx / dist) * force;
        dot.vy += (dy / dist) * force;
      }

      dot.x += dot.vx;
      dot.y += dot.vy;
    }
  }

  function drawDots() {
    for(var i = 0; i < dots.nb; i++){
      dots.array[i].draw();
    }
  }

  function animateDots() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    moveDots();
    drawDots();
    requestAnimationFrame(animateDots); 
  }

  $('canvas').on('mousemove', function(e){
    mousePosition.x = e.pageX;
    mousePosition.y = e.pageY;
    mouseActive = true;
  });

  $('canvas').on('mouseleave', function(e){
    mousePosition.x = canvas.width / 2;
    mousePosition.y = canvas.height / 2;
    mouseActive = false;
  });

  createDots();
  requestAnimationFrame(animateDots);
});
</script>


上一篇:视频比例计算方法

下一篇:已经是最后一篇

评论区

共 0 条评论
  • 这篇文章还没有收到评论,赶紧来抢沙发吧~

【随机内容】

返回顶部