浪漫的html星空源代码
时间: 2023-12-25 16:04:35 浏览: 47
以下是一个浪漫的HTML星空源代码,使用了HTML5的canvas标签和JavaScript实现:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>浪漫的星空</title>
<style>
body {
margin: 0;
padding: 0;
background-color: #000;
}
canvas {
display: block;
position: fixed;
top: 0;
left: 0;
z-index: -1;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
// 设置canvas的宽高
canvas.width = window.innerWidth; canvas.height = window.innerHeight;
// 星星的数量
var starsCount = 500;
// 定义星星的构造函数
function Star() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.size = Math.random() * 3;
this.speed = Math.random() * 0.5;
}
// 创建星星数组
var stars = [];
for (var i = 0; i < starsCount; i++) {
stars.push(new Star());
}
// 绘制星星
function drawStars() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#ffffff';
for (var i = 0; i < stars.length; i++) {
var star = stars[i];
ctx.beginPath();
ctx.arc(star.x, star.y, star.size, 0, Math.PI * 2);
ctx.fill();
}
}
// 更新星星的位置
function updateStars() {
for (var i = 0; i < stars.length; i++) {
var star = stars[i];
star.x += star.speed;
if (star.x > canvas.width) {
star.x = 0;
}
}
}
// 动画循环
function loop() {
requestAnimationFrame(loop);
drawStars();
updateStars();
}
// 启动动画循环
loop();
</script>
</body>
</html>
```
相关推荐
![html](https://img-home.csdnimg.cn/images/20210720083451.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)
![](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)
![](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)