温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用canvas怎么实现一个粒子动画背景

发布时间:2021-04-07 16:49:13 来源:亿速云 阅读:263 作者:Leah 栏目:web开发

使用canvas怎么实现一个粒子动画背景?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

创建canvas

首先需要在需要展示粒子背景的父元素中创建一个canvas标签, 指定widthheight, 在我们生成随机点坐标的时候需要用widthheight来做参照。widthheight等于父元素的宽和高。

// 假如父元素是body const ele = document.body; const canvas = document.createElement('canvas'); canvas.width = ele.clientWidth; canvas.height = ele.clientHeight; // 将canvas标签插入 ele.appendChild(canvas);

随机生成一定数量的点坐标信息

widthheight做参照随机生成一定数量的点坐标信息,包含x, y, rateX(点在X轴的移动速率), rateY(点在Y轴移动的速率), rateXrateY决定了点的运动轨迹。

const points = []; // 随机生成点的坐标,需指定radius的最大值 function getPoint(radius) {   const x = Math.ceil(Math.random() * this.width), // 粒子的x坐标     y = Math.ceil(Math.random() * this.height), // 粒子的y坐标     r = +(Math.random() * this.radius).toFixed(4), // 粒子的半径     rateX = +(Math.random() * 2 - 1).toFixed(4), // 粒子在x方向运动的速率     rateY = +(Math.random() * 2 - 1).toFixed(4); // 粒子在y方向运动的速率   return { x, y, r, rateX, rateY }; } // 随机生成100个点的坐标信息 for (let i = 0; i < 100; i++) {   points.push(this.getPoint()); }

将生成的点数组画到canvas上

function drawPoints() {   points.forEach((item, i) => {     ctx.beginPath();     ctx.arc(item.x, item.y, item.r, 0, Math.PI*2, false);     ctx.fillStyle = '#fff';     ctx.fill();     // 根据rateX和rateY移动点的坐标     if(item.x > 0 && item.x < width && item.y > 0 && item.y < height) {       item.x += item.rateX * rate;       item.y += item.rateY * rate;     } else {       // 如果粒子运动超出了边界,将这个粒子去除,同时重新生成一个新点。       points.splice(i, 1);       points.push(getPoint(radius));     }   }); }

画线

遍历点数组,两两比较点坐标,如果两点之间距离小于某个值,在两个点之间画一条直线,lineWidth随两点之间距离改变,距离越大,线越细。

// 计算两点之间的距离 function dis(x1, y1, x2, y2) {   var disX = Math.abs(x1 - x2),     disY = Math.abs(y1 - y2);   return Math.sqrt(disX * disX + disY * disY); } function drawLines() {   const len = points.length;   //对圆心坐标进行两两判断   for(let i = 0; i < len; i++) {     for(let j = len - 1; j >= 0; j--) {       const x1 = points[i].x,         y1 = points[i].y,         x2 = points[j].x,         y2 = points[j].y,         disPoint = dis(x1, y1, x2, y2);       // 如果两点之间距离小于150,画线       if(disPoint <= 150) {         ctx.beginPath();         ctx.moveTo(x1, y1);         ctx.lineTo(x2, y2);         ctx.strokeStyle = '#fff';         //两点之间距离越大,线越细,反之亦然         ctx.lineWidth = 1 - disPoint / distance;         ctx.stroke();       }     }   } }

动画

使用requestAnimationFrame循环调用draw方法(draw方法里包含画点和画线),同时在draw的时候根据rateXrateY来改动点的位置。

// 调用draw函数开启动画 (function draw() {   ctx.clearRect(0, 0, width, height);   drawPoints();   // 如果不需要画线,取消下面这行代码即可。   drawLines();   window.requestAnimationFrame(draw); }());

看完上述内容,你们掌握使用canvas怎么实现一个粒子动画背景的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI