写一段代码,在网页上打开可以看到很多小星星的
时间: 2023-03-21 21:03:03 浏览: 54
以下是一个基于 JavaScript 的代码段,可以在网页上生成许多小星星:
```html
<!DOCTYPE html>
<html>
<head>
<title>小星星</title>
<style>
body {
margin: 0;
padding: 0;
}
canvas {
background-color: black;
}
</style>
</head>
<body>
<canvas id="myCanvas"></canvas>
<script>
// 获取画布
var canvas = document.getElementById("myCanvas");
// 设置画布宽度和高度
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 获取画笔
var ctx = canvas.getContext("2d");
// 定义一个星星对象
function Star() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.radius = Math.random() * 1.5;
this.color = "white";
}
// 定义一个星星数组
var stars = [];
// 生成一定数量的星星
for (var i = 0; i < 1000; i++) {
stars.push(new Star());
}
// 绘制星星
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < stars.length; i++) {
var star = stars[i];
ctx.beginPath();
ctx.arc(star.x, star.y, star.radius, 0, Math.PI * 2);
ctx.fillStyle = star.color;
ctx.fill();
}
}
// 循环绘制
setInterval(draw, 30);
</script>
</body>
</html>
```
这个代码使用了 HTML5 的 Canvas 元素和 JavaScript 来生成一定数量的随机位置、随机大小和随机颜色的小星星,并且以一定的速度不断循环地在画布上绘制。可以将这个代码保存成一个 .html 文件,用浏览器打开即可看到小星星的效果。