前端canvas粒子动画背景(带鼠标跟随和点击散开) |
您所在的位置:网站首页 › 鼠标跟踪怎么设置 › 前端canvas粒子动画背景(带鼠标跟随和点击散开) |
目录 闲聊 看下效果 先贴下代码吧 大概说一下流程 下面让我来详细说一下 1、初始化基础属性 2、添加鼠标移动事件并实时更新鼠标坐标 3、通过随机数生成粒子的坐标和横纵轴速度 4、渲染粒子并将粒子对象保存在数组中 5、调用requestAnimationFrame启动动画,使粒子移动起来 6、通过横纵坐标和速度计算粒子位置 7、计算与鼠标距离进行坐标的修正 8、计算与鼠标距离并进行连线 9、计算粒子直接的距离并进行连线 10、添加鼠标点击事件并调用粒子的散开事件 11、通过与鼠标的距离和相对位置进行计算来重新给粒子添加速度 12、监听页面大小变化来初始化画布 总结 闲聊一年前觉得别人写的贼酷贼神奇的canvas粒子动画背景,一年后自己写了一个更nb的,hahahaha! 好吧,其实也没啥难的,前后大概花了俩小时,只不过是最近才正儿八经学了一下canvas,写个东西来练练手。 言归正传,这个粒子背景的粒子移动和粒子直接的连线以及和鼠标的连线都很简单,两个难点在于鼠标跟随和点击散开,下面的介绍中我将重点说一下这两个功能点。 看下效果没有鼠标?截图给隐藏掉了,位置就不用我说了吧。 gif好糊啊= = 先贴下代码吧 Starry const canvas = document.getElementById('canvas') const ctx = canvas.getContext('2d') let width = window.innerWidth let height = window.innerHeight let dotsNum = 80 // 点的数量 let radius = 1 // 圆的半径,连接线宽度的一半 let fillStyle = 'rgba(255,255,255,0.5)' // 点的颜色 let lineWidth = radius * 2 let connection = 120 // 连线最大距离 let followLength = 80 // 鼠标跟随距离 let dots = [] let animationFrame = null let mouseX = null let mouseY = null function addCanvasSize () { // 改变画布尺寸 width = window.innerWidth height = window.innerHeight canvas.width = width canvas.height = height ctx.clearRect(0, 0, width, height) dots = [] if (animationFrame) window.cancelAnimationFrame(animationFrame) initDots(dotsNum) moveDots() } function mouseMove (e) { mouseX = e.clientX mouseY = e.clientY } function mouseOut (e) { mouseX = null mouseY = null } function mouseClick () { for (const dot of dots) dot.elastic() } class Dot { constructor(x, y) { this.x = x this.y = y this.speedX = Math.random() * 2 - 1 this.speedY = Math.random() * 2 - 1 this.follow = false } draw () { ctx.beginPath() ctx.arc(this.x, this.y, radius, 0, 2 * Math.PI) ctx.fill() ctx.closePath() } move () { if (this.x >= width || this.x = height || this.y = 1) this.speedX-- if (this.speedX = 1) this.speedY-- if (this.speedY |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |