写一个万家灯火的发光的js背景特效
时间: 2023-11-22 16:53:39 浏览: 35
以下是一个简单的万家灯火背景特效的JS代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>万家灯火背景特效</title>
<style type="text/css">
body {
margin: 0;
padding: 0;
height: 100vh;
background-color: #000;
overflow: hidden;
}
canvas {
position: absolute;
top: 0;
left: 0;
z-index: -1;
}
</style>
</head>
<body>
<canvas id="myCanvas"></canvas>
<script type="text/javascript">
window.onload = function() {
var canvas = document.getElementById('myCanvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var ctx = canvas.getContext('2d');
var particles = [];
function Particle() {
this.x = canvas.width * Math.random();
this.y = canvas.height * Math.random();
this.vx = (Math.random() - 0.5) * 5;
this.vy = (Math.random() - 0.5) * 5;
this.radius = 5;
}
Particle.prototype.draw = function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
ctx.fill();
};
Particle.prototype.update = function() {
this.x += this.vx;
this.y += this.vy;
if (this.x < 0 || this.x > canvas.width) {
this.vx *= -1;
}
if (this.y < 0 || this.y > canvas.height) {
this.vy *= -1;
}
};
for (var i = 0; i < 1000; i++) {
particles.push(new Particle());
}
function loop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < particles.length; i++) {
particles[i].draw();
particles[i].update();
}
requestAnimationFrame(loop);
}
loop();
};
</script>
</body>
</html>
```
该代码会在页面背景中生成许多随机移动的白色圆点,效果类似于万家灯火。可以通过调整代码中的参数来改变特效的效果,例如圆点数量、运动速度、颜色透明度等。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)