附以前連接:用canvas繪製漫天飛舞的雪花1
用canvas繪製漫天飛舞的雪花3html
接上一篇 :
效果連接:https://codepen.io/andy-js/pen/QWwavJj
右鍵打開效果更好。canvas
此次將上篇的JS裝成方法,並在此基本上填加了一個初始角度的設置。
以方法隨時調用。segmentfault
直接上代碼:app
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>andy-js:用canvas繪製漫天飛舞的雪花2</title> <style> *{margin:0;padding:0} </style> </head> <body> <script> class Snowflake{ constructor(ctx){ this.ctx=ctx; }; render({width,x,y,angle}){ this.width=width; //雪花外框大小 this.x=x; this.y=y; this.angle=angle; this.ctx.save(); this.init(); this.bole(); this.ctx.restore(); }; init(){ //初始化 this.lineWidth=parseInt(this.width/60); //主幹線的寬度 this.lineHeight=this.width/2*0.8; //主幹線的 長度 if(this.lineHeight<1)this.lineHeight=1; this.heightArr=[ this.lineHeight*0.12,this.lineHeight*0.12,this.lineHeight*.2,this.lineHeight*0.3 ]; this.ctx.lineWidth=this.lineWidth; this.ctx.strokeStyle='#fff'; this.ctx.fillStyle="#fff"; this.ctx.translate(this.x,this.y);//從新映射畫布上的 (0,0) 位置 映射到雪花位置 //旋轉 起始度 if(this.angle!=0)this.ctx.rotate( this.angle*Math.PI/180 ); }; bole(){ for(let i=0;i<6;i++){ this.ctx.lineCap="round";//向線條的每一個末端添加圓形線帽。 this.ctx.fillStyle="#fff"; this.ctx.beginPath(); this.ctx.moveTo(0,0); this.ctx.lineTo(0,-this.lineHeight); this.ctx.stroke(); //畫頂端圓 this.ctx.beginPath(); this.ctx.arc(0,-this.lineHeight,this.lineWidth*1.5,0,Math.PI*2,true); this.ctx.fill(); //畫支線 this.branch(); //旋轉 this.ctx.rotate(Math.PI/3); }; }; branch(){ //畫分支 let lineHeight=this.lineHeight; let start=0, gap=parseInt(lineHeight /4); //每根分支的間距 for(let i=0;i<4;i++){ this.ctx.lineCap="round";//向線條的每一個末端添加圓形線帽。 let spot=this.getXY(45,this.heightArr[i]); this.ctx.beginPath(); this.ctx.moveTo(0,start); this.ctx.lineTo(spot.x, start+spot.y ); this.ctx.stroke(); this.ctx.beginPath(); this.ctx.moveTo(0,start); this.ctx.lineTo(-(spot.x), start+spot.y ); this.ctx.stroke(); start-=gap; }; }; getXY(angle,radius){ //經過正餘弦區取XY座標 return { x:Math.sin((180-angle)*Math.PI/180)*radius, y:Math.cos((180-angle)*Math.PI/180)*radius } }; background(w,h){ this.ctx.fillStyle="#000"; this.ctx.fillRect(0,0,w,h); }; }; var oC1=document.createElement('canvas'); ctx = oC1.getContext("2d"); var w=document.documentElement.clientWidth,h=800 oC1.setAttribute('width',w); oC1.setAttribute('height',h); document.body.appendChild(oC1); var renderSnow=new Snowflake(ctx); renderSnow.background(w,h); //背景刷黑 //默認畫面 var startX=50,width=30,snows=[]; while(startX<w){ let o={ ctx:ctx, width:width, x:startX, y:h/2, angle:rnd(0,360) }; snows.push(o); renderSnow.render(o); startX+=width; width+=10; }; //先簡單開個定時器 setInterval(function(){ renderSnow.background(w,h); snows.forEach(function(o){ o.angle+=15; if(o.angle>360)o.angle=o.angle%360; renderSnow.render(o); }); },100); function rnd(n,m){ return Math.random()*(m-n+1)+n; }; </script> </body> </html>
在下一篇中將繪製出漫天飛舞dom