用html js做一个鼠标粒子星星特效
时间: 2023-07-18 10:34:19 浏览: 65
好的,下面是一个简单的示例代码,可以实现鼠标移动时,产生星星特效的效果:
HTML代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>鼠标粒子星星特效</title>
<style>
canvas {
position: absolute;
top: 0;
left: 0;
z-index: -1;
}
</style>
</head>
<body>
<h1>鼠标粒子星星特效</h1>
<canvas id="canvas"></canvas>
<script src="stars.js"></script>
</body>
</html>
```
JS代码(保存为stars.js文件):
```javascript
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
stars = [],
maxStars = 100;
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
function Star() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.radius = Math.random() * 2;
this.vx = Math.random() * 0.5 - 0.25;
this.vy = Math.random() * 0.5 - 0.25;
}
Star.prototype.move = function() {
this.x += this.vx;
this.y += this.vy;
if (this.x < -this.radius || this.x > canvas.width + this.radius) {
this.vx = -this.vx;
}
if (this.y < -this.radius || this.y > canvas.height + this.radius) {
this.vy = -this.vy;
}
}
Star.prototype.draw = function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = '#fff';
ctx.fill();
}
function drawStar() {
for (var i = 0; i < maxStars; i++) {
stars[i].move();
stars[i].draw();
}
}
function init() {
for (var i = 0; i < maxStars; i++) {
stars[i] = new Star();
}
setInterval(function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawStar();
}, 30);
}
init();
canvas.addEventListener('mousemove', function(e) {
for (var i = 0; i < maxStars; i++) {
var dx = e.clientX - stars[i].x,
dy = e.clientY - stars[i].y,
distance = Math.sqrt(dx * dx + dy * dy),
force = -distance / 1000;
if (distance < 100) {
stars[i].vx += dx * force;
stars[i].vy += dy * force;
}
}
});
```
这段代码实现了鼠标移动时,产生星星特效的效果。具体实现方式是:首先定义一个Star对象,包含星星的位置、大小、速度等属性,并定义move和draw方法分别用于更新星星的位置和绘制星星。然后在init函数中,初始化100个星星,并使用setInterval定时更新画面。最后,使用canvas的mousemove事件,来控制星星的运动方向和速度。
这只是一个简单的示例代码,如果需要更加复杂的效果,可以根据实际需求进行修改和扩展。