warea = {x: null, y: null}; var animateHeader = document.getElementById("animateHeader"); animateHeader.onmousemove = function (e) { e = e || window.event; warea.x = e.clientX + 10; warea.y = e.clientY; };
保存了鼠标位置后,在每次动画循环的时候,把鼠标位置也当成一个粒子对象塞进数组进行比较:
animate() { ctx.clearRect(0, 0, canvas.width, canvas.height); bubDrawLine([warea].concat(dots)); RAF(animate); }
而粒子往鼠标方向运动的代码,其实就这么一小截:
(ndot === warea && dis < 20000) { dot.x -= xc * 0.01; dot.y -= yc * 0.01; }
计算鼠标与粒子的距离,当鼠标与粒子之间的距离小于一定的时候,把粒子的位置更新为 “当前位置 - 鼠标粒子距离 * 0.01”即可。然后就会形成粒子往鼠标位置移动的效果了。
整个效果就这样完成了,很简单,也很有意思,有兴趣的可以去研究一下发掘一些更好玩的效果。
贴上这个demo的github地址:https://github.com/whxaxes/canvas-test/blob/gh-pages/src/Funny-demo/nets.html
这个demo是很早之前写的,跟上面贴出来的代码会有点出入,但是原理是一样的。懂了原理,就可以自己去实现一个了。
如果觉得demo不错,就在github给个star呗,当然也欢迎fork