酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

js 生成雪花

以下是一个使用 JavaScript 生成雪花效果的简单示例代码: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>雪花效果</title> <style> body { overflow: hidden; background-color: black; } </style> </head> <body> <script> // 雪花类 class Snowflake { constructor() { this.x = Math.random() * window.innerWidth; this.y = -10; // 从顶部开始 this.speed = Math.random() * 3 + 1; // 下落速度 this.size = Math.random() * 3 + 1; // 雪花大小 } update() { this.y += this.speed; if (this.y > window.innerHeight) { this.y = -10; this.x = Math.random() * window.innerWidth; } } draw(ctx) { ctx.beginPath(); ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI); ctx.fillStyle = "white"; ctx.fill(); } } // 初始化 let canvas = document.createElement('canvas'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; document.body.appendChild(canvas); let ctx = canvas.getContext('2d'); let snowflakes = []; for (let i = 0; i < 100; i++) { // 生成 100 个雪花 snowflakes.push(new Snowflake()); } // 动画循环 function animate() { ctx.clearRect(0, 0, window.innerWidth, window.innerHeight); for (let snowflake of snowflakes) { snowflake.update(); snowflake.draw(ctx); } requestAnimationFrame(animate); } animate(); </script> </body> </html> ``` 这段代码创建了一个雪花类,每个雪花有随机的位置、速度和大小。通过不断更新雪花的位置并重新绘制,实现了雪花下落的效果。 [2024-09-14 14:32:23 | AI写代码神器 | 560点数解答]

相关提问