小程序:使用画布制作文本效果
浏览:372 次

首先,上图显示了最终效果:
再看看闪光效果:
现在让我们来谈谈简单的实现思路:1.首先在画布中绘制文本;
2.使用getImageData()获取图像数据;
3.以一定间隔获取图像数据中黑色(可以使用其他颜色)的值(获取坐标);
4.在获得的坐标中绘制一个矩形(也可以绘制其他形状);
5.使用requestAnimationFrame变换矩形颜色。
这将闪烁~~

最后,代码vari=0
第页({
/***页面的初始数据*/数据:{hideNav:false,颜色:[“#fff”,“#FF6E40”,“#FFAB40”,”#FFFF00“,”#EEFF41“,”#1B2FF59“,”#69F0AE“,”“#64FFDA”,“#18FFFF”,”#40C4FF“,
文本:“肖战”,滚动:假,设置:假},
/***生命周期函数--侦听页面加载*/onLoad:函数(选项){let that=this,text=wx.getStorageSync('linkText')|| this.data.text;this.setData({text})this。初始化()},
init(){wx.createSelectorQuery().select('#canvas').fields({节点:true,大小:true)。exec((res)=>{让它=this,text=this.data.textconst width=res[0].widthconst height=res[0].height
const canvas=res[0]。nodeconst ctx=画布。getContext('2d')常量dpr=1//wx.getSystemInfoSync().pixelRatiocanvas。宽度=宽度*dprcanvas。高度=高度*dprctx。scale(dpr,dpr)i=(canvas.width-that.getByteLen(text)*100)/2ctx。fillStyle=“#ffffff”;ctx。fillRect(0,0,画布宽度,画布高度);ctx。font=“bold 200px Arial”;ctx。fillStyle=“黑色”;ctx。textBaseline=“顶部”;ctx。fillText(文本,0,100);//ctx。lineWidth=5;//ctx。strokeText(文本,0,100);让imageData=ctx。getImageData(0,0,canvas.width,canvas.height)。数据;//console.log(图像数据)
ctx。fillStyle=“#ffffff”;ctx。fillRect(0,0,画布宽度,画布高度);

此数据。canvas=canvathis.data。ctx=ctxthis.data。imageData=imageDataconsole.log(canvas.width,canvas.height)//this。drawText()常量renderLoop=()=>{this.drawText()
canvas.requestAnimationFrame(renderLoop)}//canvas.cancelAnimationFrame(render Loop)画布。requestAnimationFrame(renderLoop)})},drawText(){var gap=7,{imageData,canvas,ctx,text,scroll}=this。dataif(滚动){if(i>=canvas.width){i=-cans.width}i+=2}
ctx。clearRect(0,0,canvas.width,canvas.height)用于(var h=0;h 如果(r+g+b==0){ctx.fillStyle=this.data.colors[Math.floor(Math.random()*this.data.coolors.length)];ctx.fill Rect(w+i,h,5,5);}} },toggleSettings(){this.setData({setting:this.data.setting?false:true})},setText(e){ 让它=thiswx.cloud。callFunction({name:“msgSecCheck”,数据:{op:“textCheck”、内容:e.detail.value}、成功(res){console.log(“ContentCheck-res”,res)if(res.result.code==300){控制台.log(res-result.msg)wx.showToast({icon:“none”,标题:res.result.msg,})。setData({'text':“”})}其他{that。setData({setting:false,'text':e.detail.value})。init()}},失败(错误){console.log('ContentCheck-errxxxx',错误) }}) },getByteLen(str){var len=0;对于(var i=0;i