<style> * { margin: 0; padding: 0; } :root, html, body { width: 100vw; height: 100vh; } #canvas { background-color: #000000; } </style> <canvas id='canvas'></canvas> <script> var canvas = document.getElementById('canvas'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; var ctx = canvas.getContext("2d"); // 初始化一个转雪花的数组 var snowArr = []; /* 雪花实例 (x,y) 是雪花对称图形的中心 r 是每条的成都 rotateDeg 是旋转角度 speedX 是水平的速度 speedY 是垂直的速度 scale 雪花的缩放大小 rotateS每一朵旋转的角度*/ function Snow(x, y, rotateDeg, speedX, speedY, scale, rotateS) { this.x = x; this.y = y; this.r = 20; this.rotateDeg = rotateDeg; this.speedX = speedX; this.speedY = speedY; this.scale = scale; this.rotateS = rotateS; } /* 画雪花*/ Snow.prototype.draw = function () { // 先保存一下最开始的状态, 方便到时候绘画多个 var x = this.r * Math.sin(Math.PI / 6), y = this.r * Math.sin(Math.PI / 3); ctx.beginPath(); ctx.save(); ctx.translate(this.x, this.y); ctx.strokeStyle = "#ffffff"; ctx.lineCap = "round"; ctx.lineWidth = 10; ctx.scale(this.scale, this.scale) ctx.rotate(this.rotateDeg * Math.PI / 180); ctx.moveTo(-this.r, 0); ctx.lineTo(this.r, 0); ctx.moveTo(-x, -y); ctx.lineTo(x, y); ctx.moveTo(-x, y); ctx.lineTo(x, -y); ctx.stroke(); ctx.restore(); } function init() { // 默认生成100朵雪花 for (let i = 0; i < 100; i++) { var x = Math.random() * canvas.width; // 雪花要从上往下掉落, 所以高度一开始都为0 var y = 0; // 水平速度大小不一致, var speedX = Math.random() + 1; //1~2 var speedY = Math.random() + 5; // 每朵雪花的大小不一样 倍数为0.5~1.5 var scale = Math.random() + 0.5; var rotateS = Math.random()*4 + 2; //2~6 // 旋转的角度 var rotateDeg = Math.random() * 60; (function (x, y, rotateDeg, speedX, speedY, scale,rotateS) { setTimeout(() => { var snow = new Snow(x, y, rotateDeg, speedX, speedY, scale, rotateS); snow.draw(); snowArr.push(snow); }, Math.random() * 8000); })(x, y, rotateDeg, speedX, speedY, scale,rotateS) } snowing() } // 让雪花飞起来 function snowing() { setInterval(() => { ctx.clearRect(0, 0, canvas.width, canvas.height) console.log(1321321) snowArr.forEach(ele => { ele.x = (ele.x + ele.speedX) % canvas.width; ele.y = (ele.y + ele.speedY) % canvas.height; ele.rotateDeg = (ele.rotateDeg + ele.rotateS) % 60; ele.draw(); }) }, 30); } init(); </script>
效果如下: