【Canvas】锯锯齿左右开门效果
作者:互联网
源码下载:https://files.cnblogs.com/files/heyang78/imma220107.rar
如果不知道锯锯齿左右开门效果为何物,请看下面三张效果图:
1.
2.
3.
代码:
<!DOCTYPE html> <html lang="utf-8"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <head> <title>锯锯齿开门效果</title> <style type="text/css"> .centerlize{ margin:0 auto; border:0px solid red; width:960px;height:540px; } </style> </head> <body onl oad="draw();"> <div class="centerlize"> <canvas id="myCanvas" width="960px" height="540px" style="border:1px dashed black;"> 出现文字表示你的浏览器不支持HTML5 </canvas> </div> </body> </html> <script type="text/javascript"> <!-- // 画布宽度 const WIDTH=960; // 画布高度 const HEIGHT=540; // 左右活动版之间的间隔 var gap=0; //------------------------------- // 开始绘制 //------------------------------- function draw(){ var canvas=document.getElementById('myCanvas'); canvas.width=WIDTH; canvas.height=HEIGHT; context=canvas.getContext('2d'); context.translate(WIDTH/2,HEIGHT/2); slot=new Slot(); animate(); }; //------------------------------- // 有条件执行动画 //------------------------------- function animate(){ slot.update(gap); slot.paintBg(context); slot.paint(context); gap+=1; // 241=Max(obj.boards)*2+1 if(gap<WIDTH+241){ window.requestAnimationFrame(animate); } } //------------------------------- // 光阑对象 //------------------------------- function Slot(){ var obj=new Object; obj.gap=0; obj.img=new Image(); obj.img.src="imma.png"; obj.boards=[120,80,40,0,-40,-80,-120,-80,-40,0,40,80,120]; // 计算 obj.update=function(gap){ this.gap=gap; }; // 画背景图片 obj.paintBg=function(ctx){ context.drawImage(this.img,0,0,WIDTH,HEIGHT,-WIDTH/2,-HEIGHT/2,WIDTH,HEIGHT); }; // 画左右展开活动板 obj.paint=function(ctx){ var n=this.boards.length; var boardWidth=HEIGHT/n; for(var i=0;i<n;i++){ var board=this.boards[i]; var x1=0+(-WIDTH/2); var y1=i*boardWidth+(-HEIGHT/2); var w1=WIDTH/2+board-this.gap/2; var h1=boardWidth; ctx.fillStyle=getColor(i); ctx.fillRect(x1,y1,w1,h1); var x2=board+this.gap/2; var y2=i*boardWidth+(-HEIGHT/2); var w2=(WIDTH)-board-this.gap/2; var h2=boardWidth; ctx.fillStyle=getColor(i); ctx.fillRect(x2,y2,w2,h2); } }; return obj; } //------------------------------- // 角度得到弧度 //------------------------------- function getRad(degree){ return degree/180*Math.PI; } //------------------------------- // 得到颜色 //------------------------------- function getColor(index){ var arr=["green","skyblue","purple","#aa0000", "orange","yellow","maroon","navy", "red","blue","lime","teal","fuchsia", "aqua","black"]; if(index>arr.length){ index=index % arr.length; } return arr[index]; } //--> </script>
以上代码难度不大,主要利用数组造成锯齿效果,然后计算好每个矩形的起点和高宽就好。懂得都懂,就不赘述了。
END
标签:files,index,Canvas,效果,开门,arr,锯齿,length 来源: https://www.cnblogs.com/pyhy/p/15780317.html