帮我用js写一段代码。输出:雪花下落的动态效果
时间: 2023-03-02 12:41:28 浏览: 61
好的,以下是一段用 JavaScript 实现的雪花下落动态效果的代码:
```javascript
// 获取 canvas 元素
const canvas = document.getElementById('snow');
// 获取绘制上下文
const ctx = canvas.getContext('2d');
// 设置画布宽高为窗口宽高
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 雪花数量
const snowflakesCount = 100;
// 存储所有雪花的状态
const snowflakes = [];
// 雪花类
class Snowflake {
constructor() {
this.x = Math.random() * canvas.width;
this.y = -Math.random() * canvas.height;
this.radius = Math.random() * 4 + 1;
this.speed = Math.random() * 3 + 1;
}
// 绘制雪花
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = 'white';
ctx.fill();
}
// 更新雪花状态
update() {
this.y += this.speed;
// 雪花飘出画布时重新随机位置和速度
if (this.y > canvas.height) {
this.x = Math.random() * canvas.width;
this.y = -Math.random() * canvas.height;
this.speed = Math.random() * 3 + 1;
}
}
}
// 初始化雪花
for (let i = 0; i < snowflakesCount; i++) {
snowflakes.push(new Snowflake());
}
// 绘制动画
function animate() {
// 清空画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制雪花并更新状态
snowflakes.forEach((snowflake) => {
snowflake.draw();
snowflake.update();
});
// 循环调用动画函数
requestAnimationFrame(animate);
}
// 启动动画
animate();
```
你可以将上述代码复制到一个 HTML 文件中,并在 body 标签内添加一个 ID 为 `snow` 的 canvas 元素,即可看到雪花下落的动态效果。