js实现跟随鼠标粒子效果
时间: 2024-01-03 17:53:46 浏览: 33
以下是一个简单的js代码实现跟随鼠标粒子效果:
HTML:
```html
<canvas id="canvas"></canvas>
```
CSS:
```css
#canvas {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
```
JS:
```javascript
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var particles = [];
var mouse = {
x: undefined,
y: undefined
}
window.addEventListener("mousemove", function(event) {
mouse.x = event.x;
mouse.y = event.y;
});
function Particle(x, y, radius, color) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
this.radians = Math.random() * Math.PI * 2;
this.velocity = 0.05;
this.distanceFromCenter = Math.random() * 50 + 100;
this.lastMouse = {x: x, y: y};
this.draw = function(lastPoint) {
ctx.beginPath();
ctx.strokeStyle = this.color;
ctx.lineWidth = this.radius;
ctx.moveTo(lastPoint.x, lastPoint.y);
ctx.lineTo(this.x, this.y);
ctx.stroke();
ctx.closePath();
}
this.update = function() {
// 记录上一帧的鼠标位置
this.lastMouse.x += (mouse.x - this.lastMouse.x) * 0.05;
this.lastMouse.y += (mouse.y - this.lastMouse.y) * 0.05;
// 运动轨迹
this.radians += this.velocity;
this.x = this.lastMouse.x + Math.cos(this.radians) * this.distanceFromCenter;
this.y = this.lastMouse.y + Math.sin(this.radians) * this.distanceFromCenter;
this.draw(this.lastMouse);
}
}
function init() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
for (var i = 0; i < 50; i++) {
var radius = Math.random() * 3 + 1;
var color = "rgba(255, 255, 255, 0.5)";
particles.push(new Particle(canvas.width / 2, canvas.height / 2, radius, color));
}
}
function animate() {
requestAnimationFrame(animate);
ctx.fillStyle = "rgba(0, 0, 0, 0.1)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < particles.length; i++) {
particles[i].update();
}
}
init();
animate();
```
这段代码创建了一个画布,并且在鼠标移动时跟随鼠标移动的粒子效果。