这是最近小编在做博客时想到的网页特效
1.鼠标动画主类
class MouseMoveAnimation {
constructor() {
// 用于存储圆球的数组
this.circlePool = [];
this.init();
}
// 初始化
init() {
this.canvas = document.createElement("canvas");
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
this.context = this.canvas.getContext("2d");
this.canvas.style.cssText = `
position: fixed;
left:0;
top:0;
z-index:9999;
pointer-events: none;
`;
document.body.appendChild(this.canvas);
document.addEventListener("mousemove", (e) => {
const circle = new Circle({
x: e.clientX, //圆心x轴坐标
y: e.clientY, //圆心y轴坐标
r: Math.random() * 50, //圆球半径
});
this.circlePool.push(circle);
});
}
// 更新特效
update() {
this.context.clearRect(0, 0, window.innerWidth, window.innerHeight);
this.circlePool.forEach((circle, index) => {
circle.render(this.context);
circle.update();
if (circle.r <= 0) {
this.circlePool.splice(index, 1);
}
});
}
// 特效开始
start() {
setInterval(() => {
this.update();
}, 20);
}
}
2.圆球类
class Circle {
constructor({ x, y, r }) {
this.x = x;
this.y = y;
this.r = r;
this.color = `rgba(${this.randomColor()},${this.randomColor()},${this.randomColor()},${Math.random()})`;
this.moveY = this.moveX = Math.random() * 10 - 5;
}
// 渲染圆球
render(context) {
context.beginPath();
context.arc(this.x, this.y, this.r, 0, Math.PI * 2);
context.fillStyle = this.color;
context.closePath();
context.fill();
}
// 更新圆球状态
update() {
this.x += this.moveX;
this.y += this.moveY;
this.r--;
}
// 返回随机颜色
randomColor() {
return Math.round(Math.random() * 255);
}
}
3.如何运用
new MouseMoveAnimation().start();// 运行这行代码,特效即可生效