<canvas>有意思的的粒子效果

本文介绍了一款使用HTML5 Canvas实现的粒子效果,包括粒子动画的实现原理与代码解析。通过构造函数封装,使得该效果可复用于不同项目。

<canvas>有意思的粒子效果

这两天突然有点儿空闲下来,闲着无聊东搜搜西看看,发现一款用canvas写的 粒子效果 挺棒的。在阅读了大神的源码以后自己参照着封装了一个构造函数,用来以后项目可能出现的使用,详情源码可以移步 这里

先晾一个 demo 给大家看看吧,因为小球数量比较多,因此无可避免的存在一些卡顿,当然也因为自己当前技术还比较粗糙,后期有机会会进行优化的。

使用说明可以参考git上的 README,因此这儿做一些代码分析吧:

  var canvas = document.querySelector(element);
  this.canvas = canvas;
  this.ctx = canvas.getContext("2d");

声明canvas,并获得上下文。

 // defaultOpts为默认属性,当开发人员没有填写时默认使用的参数
  var defaultOpts = {  
        total: 300, // 粒子总数
        color: "#AAAAAA", // 粒子和连接线的颜色
        size: 2, // 粒子大小
        width: this.canvas.parentNode.clientWidth, // canvas的宽度
        height: this.canvas.parentNode.clientHeight // canvas的高度
  };
  var opts = opts || defaultOpts;
  for (var key in opts) {
      defaultOpts[key] = opts[key];
  };
  for (var key in defaultOpts) {
      this[key] = defaultOpts[key]; // 给MoveBalls添加其余几个属性
  };
  opts = null; // 清空对象
  defaultOpts = null; // 清空对象

根据第二个参数的属性和值,来选择是使用开发人员提供的还是默认的参数,并最后将两个对象清空。

  // requestAnimationFrame兼容处理
  window.requestAnimationFrame = window.requestAnimationFrame ||
                                 window.webkitRequestAnimationFrame || 
                                 window.mozRequestAnimationFrame || 
                                 window.oRequestAnimationFrame || 
                                 window.msRequestAnimationFrame ||
                                 function(callback) {
                                    window.setTimeout(callback, 1000 / 60);
                                  };

关于 requestAnimationFrame 这个H5新的API的相关内容可以移步 张大神 这儿, requestAnimationFrame 核心是利用了 递归 的方法来进行动画渲染;

上述操作是为了做 兼容处理, 如果当浏览器不存在任意一个 requestAnimationFrame 方法,即采用 setTimeout 并将时间设置为 16ms 来弥补该API的缺失。

之后进入 MoveBalls 的构造函数 prototype 增加其他的方法:

init: function () {
    var _this = this; // 声明_this变量防止this在其它函数内部被改变为不同的对象
    this.freshResize(); // 添加重构事件,当页面大小改变后,改变canvas大小
    this.mouseEvent(); // 添加鼠标进入和离开事件,当进入后,检测鼠标坐标,四周的小球向鼠标位置移动
    this.getDots(); // 创建小球数组,涵盖的每一个对象拥有坐标和移动距离等属性
    var timer = setTimeout(function () {
      _this.draw(_this); // 核心代码为 draw() 方法
    }, 100);
  }

this.getDots() 之中,主要做粒子的数组创建:

  getDots: function () {
    while(this.count < this.total) { // while的执行效率高于for循环
      var x = Math.random() * this.canvas.width; // 横坐标
      var y = Math.random() * this.canvas.height; // 纵坐标
      var xMove = Math.random() * 2 - 1; // 横向移动距离,利用 Math.randown() 的结果 * 2 - 1,保证结果有正有负
      var yMove = Math.random() * 2 - 1; // 纵向移动距离,同上
      this.dots.push({
        x: x,
        y: y,
        xMove: xMove,
        yMove: yMove,
        max: 100 // 最大连线距离,当两个小球的距离大于它的时候断开,否则连上
      });
      this.count ++;
    }
  }

this.draw() 之中,大概有如下逻辑:

1、画出小球
  1. 给每个小点自增随机生成的移动距离(因为有正有负,所以会有增加/减少的结果);
  2. 判断是否碰壁(x > canvas.width || x < 0),让移动距离 *-1,开始反向移动;
  3. 把所有小点直接渲染在canvas里。
2、画出连线
  1. 遍历所有小球,判断彼此的距离是否小于max值,小于则连上;
  2. 根据距离比例,确定一个小数,用以定义两个小球连线的透明度(alpha);
  3. 获取当前鼠标对于容器的坐标(offsetX ? offsetX : layerX),并获取四周与其相近的小球,连上线并向鼠标坐标点靠近;
  4. 将线条渲染 。
3、动画

使用之前兼容处理过的 window.requestAnimationFrame ,递归调用 this.draw() 来进行动画展现。

具体代码实现如下:

1、画出小球
    var _this = self || this; // 防止this改变
    var ctx = _this.ctx; // 接下来会多次使用到 this.ctx, 利用一个变量声明
    ctx.clearRect(0, 0, _this.canvas.width, _this.canvas.height); // 清除画布
    _this.newDots = [_this.coordinate].concat(_this.dots); // 建立一个新的数组,存放所有小点以及鼠标坐标
    _this.dots.forEach(function (dot) {
      dot.xMove *= (dot.x > _this.canvas.width || dot.x < 0) ? -1 : 1; // 小球横向移动的距离,并做碰壁处理
      dot.yMove *= (dot.y > _this.canvas.height || dot.y < 0) ? -1 : 1; // 纵向移动距离
      dot.x += dot.xMove;
      dot.y += dot.yMove;
      ctx.save(); // 入栈
      ctx.beginPath();
      ctx.arc(dot.x, dot.y, _this.size, 0, Math.PI * 2); // 画球
      ctx.fillStyle = _this.color;
      ctx.fill();
      ctx.restore(); // 出栈
      ...
      ...
      ...
    });
2、画出连线
     _this.dots.forEach(function (dot) {
      // 循环比对粒子间的距离
      for (var i = 0; i < _this.newDots.length; i ++) {
        var newDot = _this.newDots[i]; // 声明一个变量用于储存每次遍历的结果,方便后续操作
        if(newDot === dot || newDot.x === null || newDot.y === null) continue;         // 如果是第一个点,则跳过
        // 这儿就是采用for循环而不用 forEach() 的缘由,需要做continue跳出某轮循环,减少计算量
        var xDistance = dot.x - newDot.x; // 两个点的距离
        var yDistance = dot.y - newDot.y;
        var distance = Math.sqrt(Math.pow(xDistance, 2) + Math.pow(yDistance, 2)); // 根据勾股定理,获取两个点的距离
        var deep = 0; // 颜色深度
        if (distance <= newDot.max) { // 小于等于最小距离,则连线
          if(newDot === _this.coordinate && distance > (newDot.max / 2)) { // 附近的小球向鼠标位置移动,当小球离鼠标坐标小于连线距离的1/2时,则停止靠近,按照dots.xMove和dots.yMove做自己的移动
            dot.x -= xDistance * 0.03;
            dot.y -= yDistance * 0.03;
          }
          deep = (newDot.max - distance) / newDot.max; // 距离越近---值越大---颜色越深
          ctx.save(); // 入栈
          ctx.beginPath();
          ctx.lineWidth = deep / 2;
          var colorInfo = _this.colorCheck(); // 调用colorCheck()方法,正则获取颜色的rgb数值,形成一个length = 3的数组
          ctx.strokeStyle = "rgba(" + colorInfo[0] + ", " + colorInfo[1] + ", " + colorInfo[2] + "," + (deep + 0.4) + ")";
          ctx.moveTo(dot.x, dot.y);
          ctx.lineTo(newDot.x, newDot.y);
          ctx.stroke();
          ctx.restore(); // 出栈
        }
      }
      _this.newDots.splice(_this.newDots.indexOf(dot), 1);
    });

这块儿有两个小tips,一个是关于 ctx.save()ctx.restore() ,另一个是 _this.newDots.splice(_this.newDots.indexOf(dot), 1)

第一个的处理是为了防止canvas的第二次操作受到第一次操作结束后的路径影响,具体可以参考 这儿 ,虽然这次单独的画圆并没有什么影响,不过依然可以保留这两段方法,更加保险 XD;

第二个的处理是将处理结束的粒子从数组删除,防止重复遍历,造成浏览器更大的压力。

3、动画

激动人心的最后一步动画啦,只要间简单的的一行代码即可搞定:

window.requestAnimationFrame(function (obj) {
      _this.draw(_this); // 防止this的指向变成window,从而将该构造函数的实例作为参数引入draw()方法
    });

懒猴,这个理论上就可以使用了(手动滑稽)。就酱,遁走遁走。

### 粒子爱心动画的HTML和CSS代码示例 以下是基于现有引用内容以及专业知识构建的一个完整的粒子爱心动画示例。此示例综合了HTML结构、CSS样式以及JavaScript逻辑,用于创建一个动态跳动的心形图案。 #### HTML部分 ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>粒子爱心动画</title> <style> body { margin: 0; padding: 0; overflow: hidden; background-color: #1e1e1e; /* 设置背景颜色 */ color: white; /* 文字颜色 */ font-family: Arial, sans-serif; } canvas { display: block; position: absolute; top: 0; left: 0; z-index: -1; /* 将画布置于底层 */ } .heart-container { text-align: center; position: relative; top: 50%; transform: translateY(-50%); width: 100%; } svg { fill: red; /* SVG心形填充颜色 */ animation: heartbeat 2s infinite ease-in-out; /* 动画效果 */ } @keyframes heartbeat { 0%, 100% { transform: scale(1); } 50% { transform: scale(1.2); /* 放大比例 */ } } </style> </head> <body> <div class="heart-container"> <!-- 使用SVG绘制心形 --> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 29.6" style="height: 200px;"> <path d="M27.1 4.1c-.4-.4-1-.4-1.4 0L16 13.2l-9.7-8.7c-.4-.4-1-.4-1.4 0-.4.4-.4 1 0 1.4l10.7 9.5c.4.4 1 .4 1.4 0l10.7-9.5c.4-.4.4-1 0-1.4z"/> </svg> </div> <!-- 添加Canvas层实现粒子效果 --> <canvas id="particle-canvas"></canvas> <script> // JavaScript 实现粒子效果 const canvas = document.getElementById('particle-canvas'); const ctx = canvas.getContext('2d'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; window.addEventListener('resize', () => { canvas.width = window.innerWidth; canvas.height = window.innerHeight; }); class Particle { constructor(x, y) { this.x = x || Math.random() * canvas.width; this.y = y || Math.random() * canvas.height; this.size = Math.random() * 2 + 1; this.speedX = (Math.random() - 0.5) * 10; this.speedY = (Math.random() - 0.5) * 10; this.color = `rgba(${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)}, 0.8)`; } draw() { ctx.beginPath(); ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2); ctx.fillStyle = this.color; ctx.fill(); } update() { this.x += this.speedX; this.y += this.speedY; if (this.x + this.size >= canvas.width || this.x - this.size <= 0) { this.speedX *= -1; } if (this.y + this.size >= canvas.height || this.y - this.size <= 0) { this.speedY *= -1; } this.draw(); } } let particlesArray = []; for (let i = 0; i < 100; i++) { particlesArray.push(new Particle()); } function animate() { requestAnimationFrame(animate); ctx.clearRect(0, 0, canvas.width, canvas.height); for (let particle of particlesArray) { particle.update(); } } animate(); </script> </body> </html> ``` --- ### 关键点解析 1. **HTML 结构**: 页面由两大部分组成:一个是通过`<svg>`标签定义的心形图形;另一个是通过 `<canvas>` 标签实现的粒子动画区域[^1]。 2. **CSS 样式**: - 利用了关键帧动画 (`@keyframes`) 来模拟心跳的效果,使心形周期性放大缩小[^2]。 - 背景设置为深色系 (#1e1e1e),以便突出粒子动画的颜色对比度[^3]。 3. **JavaScript 颗粒效果**: - 创建了一个名为 `Particle` 的类来管理单个颗粒的行为,包括位置、速度和大小等属性。 - 使用 `requestAnimationFrame()` 方法实现了平滑的动画更新循环,确保性能优化[^4]。 --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值