canvas动画,下雪的效果实现
<!DOCTYPE html> <html> <head> <title>下雪了</title> </head> <body> <canvas id="myCanvas" width="300" height="300" style="border:3px double #996633;"> </canvas> <script> var canvas=document.getElementById('myCanvas'); var ctx=canvas.getContext('2d'); var particles = []; function loop() { createParticles(); downParticles(); drawParticles(); window.requestAnimationFrame(loop); } window.requestAnimationFrame(loop); function createParticles() { if(particles.length <30) { particles.push({ x: Math.random()*canvas.width, y: 0, speed: 2+Math.random()*3, radius: 3+Math.random()*4, }); } } function downParticles() { for(var i in particles) { var part = particles[i]; part.y += part.speed; if(part.y > canvas.height) { part.x=Math.random()*canvas.width; part.y=0; part.speed=2+Math.random()*3; part.radius=3+Math.random()*4; } } } function drawParticles() { ctx.fillStyle = "black"; ctx.fillRect(0,0,canvas.width,canvas.height); for(var i in particles) { var part = particles[i]; ctx.beginPath(); ctx.arc(part.x,part.y, part.radius, 0, Math.PI*2); ctx.closePath(); ctx.fillStyle = "white"; ctx.fill(); } } </script> </body> </html>
给心灵一个纯净空间,让思想,情感,飞扬!