【Canvas与艺术】下雪籽特效
【要点】
控制一个点的x,y坐标及下落速度,就能画出一个雪籽;创建n个雪籽,下雪籽的模拟效果就有了。
【效果图】
【代码】
<!DOCTYPE html> <html lang="utf-8"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <head> <title>下雪籽粒子特效</title> </head> <body onload="draw()"> <canvas id="myCanvus" width="1200px" height="512px" style="border:0px dashed black;"> 出现文字表示您的浏览器不支持HTML5 </canvas> </body> </html> <script type="text/javascript"> <!-- /***************************************************************** * 将全体代码(从<!DOCTYPE到script>)拷贝下来,粘贴到文本编辑器中, * 另存为.html文件,再用chrome浏览器打开,就能看到实现效果。 ******************************************************************/ // 常量画布宽 const Width=1200; // 常量画布高 const Height=512; // 绘图上下文 var context; // 舞台对象 var stage; // 肇始函数 function draw(){ var canvas=document.getElementById('myCanvus'); canvas.width=Width; canvas.height=Height; context=canvas.getContext('2d'); stage=new Stage(800); stage.init(); animate(); }; // 循环播放动画 function animate(){ context.clearRect(0,0,Width,Height);// 清屏 stage.update(); stage.paintBg(context); stage.paintFg(context); if(true){ window.requestAnimationFrame(animate); } } // 舞台类 function Stage(count){ // 定义粒子 this.arr=new Array(count); // 初始化粒子 this.init=function(){ for(var i=0;i<this.arr.length;i++){ var item={}; item.x=Math.random()*Width; item.y=Math.random()*Height; item.vy=Math.random()*5+1; this.arr[i]=item; } } // 更新粒子的位置 this.update=function(){ this.arr.forEach(function (item, i) { // 下坠 item.y+=item.vy; // 越界归零 if(item.y>Height){ item.y=0; } }) }; // 画背景 this.paintBg=function(ctx){ // 背景黑色 ctx.fillStyle="black"; ctx.fillRect(0,0,Width,Height); }; // 画前景 this.paintFg=function(ctx){ this.arr.forEach(function (item, i) { ctx.fillStyle="white"; ctx.fillRect(item.x,item.y,3,3); }) }; } /*---------------------------------- 女人是一个国家的风向标 当女人追求知识时,这个国家是进步的; 当女人崇尚自由时,这个国家是文明的; 当女人崇拜金钱时,这个国家是腐化的; 当女人攀附权贵时,这个国家是堕落的。 --马丁.杨克 ----------------------------------*/ //--> </script>
END