欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 美景 > 前端小练习——大雪纷飞(JS没有上限!!!)

前端小练习——大雪纷飞(JS没有上限!!!)

2025/5/15 21:31:22 来源:https://blog.csdn.net/beishang_1/article/details/144246076  浏览:    关键词:前端小练习——大雪纷飞(JS没有上限!!!)

大家好,我是小黄。

具体效果:(大雪缓缓下落)

完整代码:

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>雪花形状的雪</title><style>body, html {margin: 0;padding: 0;height: 100%;overflow: hidden;background-color: #1c1c1c;}canvas {display: block;}</style>
</head>
<body><canvas id="snowCanvas"></canvas><script>const canvas = document.getElementById('snowCanvas');const ctx = canvas.getContext('2d');// 设置画布的大小为窗口大小canvas.width = window.innerWidth;canvas.height = window.innerHeight;// 雪花的数量const snowflakesCount = 200;// 雪花数组const snowflakes = [];// 绘制六边形雪花function drawSnowflake(x, y, size, angle) {ctx.save();ctx.translate(x, y);ctx.rotate(angle);ctx.beginPath();for (let i = 0; i < 6; i++) {const currentAngle = (i * Math.PI) / 3;const nextAngle = ((i + 1) * Math.PI) / 3;ctx.moveTo(0, 0);ctx.lineTo(size * Math.cos(currentAngle), size * Math.sin(currentAngle));ctx.lineTo(size * Math.cos(nextAngle), size * Math.sin(nextAngle));}ctx.closePath();ctx.fillStyle = 'white';ctx.fill();ctx.restore();}// 雪花类class Snowflake {constructor() {// 随机初始位置this.x = Math.random() * canvas.width;this.y = Math.random() * canvas.height;this.size = Math.random() * 4 + 4; // 雪花的大小(4~8)this.speed = Math.random() * 3 + 1; // 雪花的下落速度this.wind = Math.random() * 0.5 - 0.25; // 随机的风力,控制雪花的左右漂动this.angle = Math.random() * Math.PI * 2; // 雪花的旋转角度this.rotationSpeed = Math.random() * 0.02 - 0.01; // 雪花的旋转速度}// 更新雪花位置update() {this.y += this.speed; // 下落this.x += this.wind; // 左右漂移this.angle += this.rotationSpeed; // 旋转// 如果雪花掉出画布,重新设置位置if (this.y > canvas.height) {this.y = 0;this.x = Math.random() * canvas.width;}}// 绘制雪花draw() {drawSnowflake(this.x, this.y, this.size, this.angle);}}// 初始化雪花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.update();snowflake.draw();});requestAnimationFrame(animate); // 请求下一帧}// 开始动画animate();
</script>
</body>
</html>

 

各位小伙伴还在BOSS直聘hr已读不回?!试试这个宝藏小程序!大家快看这里。

创作不易,各位帅气漂亮的小伙伴点个关注再走呗!!

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词