小编给大家分享一下如何使用html5 canvas实现图片玻璃碎片特效,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
html代码
<imgsrc=“city_copy.jpg”id=“src_img”class=“hidden”><divid=“container”style=“-webkit-perspective:500px;”><div><脚本src=“delaunay.js“></script><scriptsrc=”TweenMax.min.js“></script>
js代码:
//画布设置varimageWidth=768,imageHeight=485;var顶点=[],索引,方格=[];varimage,片段=[],容器=document.getElementById('container');window.onload=function(){image=document.getElementById('src_img');triangulate();makeBoxes();makeFragments();};函数triangulate(){varx,y,dx=imageWidth/8,dy=imageHeight/8,offset=0.5;对于(vari=0;i<=imageWidth;i+=dx){for(varj=0;j<=imageHeight;j+=dy){ 如果(i&&(i!==imageWidth))x=i+randomRange(-dx*offset,dx*offset);否则x=i;if(j&&(j!==imageHeight))y=j+randomRange(-dy*偏移量,dy*偏移量);否则y=j;vertices.push([x,y]);}}指数=Delaunay.triangulate(顶点);}函数makeBoxes(){varp0,p1,p2,xMin,xMax,yMin,yMax;for(vari=0;i<index.length;i+=3){p0=顶点[indices[i+0]];p1=顶点[索引[i+1]];p2=顶点[索引[i+2]];xMin=Math.min(p0[0],p1[0],p2[0]);xMax=Math.max(p0[0],p1[0],p2[0]);yMin=Math.min(p0[1],p1[1],p2[1]); yMax=Math.max(p0[1],p1[1],p2[1]);box.push({x:xMin,y:yMin,w:xMax-xMin,h:yMax-yMin});}}函数makeFragments(){VARP0,P1,P2,盒,片段;TweenMax.set(container,{Perspective:500});vartl0=newTimelineMax({repeat:-1});for(vari=0;i<index.length;i+=3){p0=顶点[indices[i+0]];p1=顶点[索引[i+1]];p2=顶点[索引[i+2]];box=box[i/3];片段=新片段(p0,p1,p2,box);varrx=randomRange(30,60)*((i%2)?1:-1);varry=randomRange(30,60)*((i%2)?-1:1); vartl1=newTimelineMax();TweenMax.set(fragment.canvas,{y:box.y-1000});tl1.to(fragment.canvas,randomRange(0.9,1.1),{y:box.y,ease:Back.easeOut});tl1.to(fragment.canvas,0.5,{z:-100,easy:Cubic.easeIn,delay:0.4});tl1.to(fragment.canvas,randomRange(1,1.2),{rotationX:rx,rotationY:ry,z:250,alpha:0,easy:Cubic.easeOut});tl0.insert(tl1);fragment.push(fragment);container.appendChild(fragment.canvas);}}函数randomRange(min,max){ 返回min+(max-min)*Math.random();}片段=函数(v0,v1,v2,框){this.v0=v0;this.v1=v1;this.v2=v2;this.box=盒子;this.canvas=document.createElement('canvas');this.canvas.width=this.box.w;this.canvas.height=this.box.h;this.canvas.style.width=this.box.w+'px';this.canvas.style.height=this.box.h+'px';this.ctx=this.canvas.getContext('2d');TweenMax.set(this.canvas,{x:this.box.x,y:this.box.y});this.ctx.translate(-this.box.x,-this.box.y);this.ctx.beginPath();this.ctx.moveTo(this.v0[0],this.v0[1]); this.ctx.lineTo(this.v1[0],this.v1[1]);this.ctx.lineTo(this.v2[0],this.v2[1]);this.ctx.closePath();this.ctx.clip();this.ctx.drawImage(image,0,0);};//@sourceURL=pen.js
以上是“如何使用html5 canvas实现图片玻璃碎片特效”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。