上一次说到在html中间实现的炫酷canvas特效,现在我们把他拿到小程序中去用。
这里面其实难度很小,只需要实现一个函数,也就是requestanimationframe,因为这个函数在小程序中并不支持。实现这个函数其实并不难。重要的是确定一个时间多久刷新一次屏幕,这里我们用比较常规的25fps.也就是40毫秒刷新一次屏幕。
说干就干:
最后的效果录个gif来看看,从此你的小程序 说动就动。
完美重现了。最后放上源码:
index.whtml
<canvas canvas-id="mycanvas" style="background:black;width:350px;height:350px">canvas>
index.js
//index.js//获取应用实例const app = getApp()const ctx = wx.createCanvasContext('mycanvas');var M = Math, PI = M.PI, TWOPI = PI * 2, HALFPI = PI / 2, width = 350, height = 350, cx = width / 2, cy = height / 2, count = 40, sizeBase = 0.1, sizeDiv = 5, tick = 0; Page({ onReady: function (e) { this.draw() }, onLoad:function(options){ }, draw:function(){ ctx.translate(cx,cy) ctx.clearRect( -width / 2, -height / 2, width, height ); ctx.fillStyle = '#000'; var angle = tick / 8, radius = -50 + M.sin( tick / 15 ) * 100, size; for( var i = 0; i < count; i++ ) { angle += PI / 64; radius += i / 30; size = sizeBase + i / sizeDiv; //类蓝色 ctx.beginPath(); ctx.arc( M.cos( angle ) * radius, M.sin( angle ) * radius, size, 0, TWOPI, false ); ctx.setFillStyle('blue') ctx.fill(); //类红色 ctx.beginPath(); ctx.arc( M.cos( angle ) * -radius, M.sin( angle ) * -radius, size, 0, TWOPI, false ); ctx.setFillStyle('red') ctx.fill(); //类黄色 ctx.beginPath(); ctx.arc( M.cos( angle + HALFPI ) * radius, M.sin( angle + HALFPI ) * radius, size, 0, TWOPI, false ); ctx.setFillStyle('yellow') ctx.fill(); //类白色 ctx.beginPath(); ctx.arc( M.cos( angle + HALFPI ) * -radius, M.sin( angle + HALFPI ) * -radius, size, 0, TWOPI ); ctx.setFillStyle('white') ctx.fill(); } ctx.draw() tick++; setTimeout( this.draw, 40); }})
要研究更多的canvas炫酷效果,可以在 公众号 内 回复 炫酷,我已经为你打包n种炫酷效果,等你来拿。