赞
踩
基于canvas制作跟随鼠标移动的彩色圆点粒子分散动画特效 ,先来看看效果:
一部分关键的代码如下:
- <!DOCTYPE html>
- <html lang="en">
-
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title></title>
-
- <style>
- * {
- margin: 0;
- padding: 0;
- }
-
- body {
- overflow: hidden;
- }
-
- canvas {
- background-color: black;
- transition: all .2s;
- }
- </style>
-
- </head>
-
- <body>
-
- <canvas id="canvas"></canvas>
- <script circleWidth='10' id="cvs">
- /** @type {HTMLCanvasElement} */
- // 初始化画板
- const canvas = document.querySelector('#canvas');
- canvas.width = window.innerWidth;
- canvas.height = window.innerHeight;
-
- // 初始化画笔
- const cvs = canvas.getContext('2d');
- let CircleArr = [];
-
- // 实例化对象
-
- canvas.addEventListener('mousemove', function (ev) {
- let cir = new Circle(ev.pageX, ev.pageY);
- CircleArr.push(cir);
- })
-
- canvas.addEventListener('touchmove', function (ev) {
- let cir = new Circle(ev.touches[0].clientX, ev.touches[0].clientY);
- CircleArr.push(cir);
- })
-
- /**
- * 主要参数位置
- */
- function Circle(X, Y) {
- this.X = Math.floor(X);
- this.Y = Math.floor(Y);
- this.speedX = Math.floor((Math.random() - 0.5) * 4);
- this.speedY = Math.floor((Math.random() - 0.5) * 4);
- this.A = 1;
- this.R = +document.getElementById('cvs').getAttribute('circleWidth') || 20;
-
- }
-
- Circle.prototype = {
- // 画圆
- draw() {
- cvs.beginPath();
- cvs.fillStyle =
- `rgb(${Math.floor(Math.random()*255)},${Math.floor(Math.random()*255)},${Math.floor(Math.random()*255)})`;
- cvs.globalCompositeOperation = "lighter";
- cvs.globalAlpha = this.A;
- cvs.arc(this.X, this.Y, this.R, 0, Math.PI * 2);
- cvs.fill();
- this.upDate();
- },
- // 更新圆的状态
- upDate() {
- this.X += this.speedX;
- this.Y += this.speedY;
- this.A *= 0.98;
- }
- }
-
- // 清除重画
- function render() {
- cvs.clearRect(0, 0, canvas.width, canvas.height);
- CircleArr.forEach(function (ele, i) {
- ele.draw();
- // 删除已经执行完的圆优化性能
- if (ele.A < 0.03) {
- CircleArr.splice(i, 1)
- }
- });
- //关键帧的刷新
- requestAnimationFrame(render);
- }
- render()
- </script>
-
- </body>
-
- </html>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。