微信小程序使用canvas绘制倒计时圆圈和数字居中的实现
1、显示结果
2、过程:
(1)wxml + css
<!-- 每道题 -->
<view style="background-color: #fff;padding:20rpx;margin:10rpx;border-radius:20rpx;">
<!-- 倒计时30秒 -->
<view style="display: flex;justify-content: center;position: relative;align-items: center;color:#666">
<canvas canvas-id="canvasProgressbg" style="width:180rpx;height:180rpx;position: absolute;"></canvas>
<canvas canvas-id="canvasProgress" style="width:180rpx;height:180rpx;"></canvas>
</view>
</view>
(2)js
data: {
count:0, // 设置 计数器 初始为0
countTimer: null, // 设置 定时器 初始为null
downTime:30, //倒计时时间
down:null,
},
//定时器倒计时显示
countInterval: function () {
// 设置倒计时 定时器 每100毫秒执行一次,计数器count+1 ,耗时6秒绘一圈
this.data.countTimer = setInterval(() => {
if (this.data.count <= 30) {
/* 绘制彩色圆环进度条
注意此处 传参 step 取值范围是0到2,
所以 计数器 最大值 60 对应 2 做处理,计数器count=60的时候step=2
*/
this.drawCircle(this.data.count / (30/2))
this.data.count++;
this.data.downTime--;
this.setData({
count:this.data.count,
downTime:this.data.downTime
});
} else {
clearInterval(this.data.countTimer)
wx.showToast({
title: '时间到',
})
}
}, 1000)
},
//环的变化
drawCircle: function (step){
var context = wx.createCanvasContext('canvasProgress');
var gradient = context.createLinearGradient(10, 5, 5, 10);
gradient.addColorStop("0", "#2661DD"); //设置渐变
gradient.addColorStop("0.5", "#40ED94");
gradient.addColorStop("1.0", "#5956CC");
context.setLineWidth(6); //圆环的宽度
context.setStrokeStyle(gradient);
context.setLineCap('round')
context.beginPath();
// 参数step 为绘制的圆环周长,从0到2为一周 。 -Math.PI / 2 将起始角设在12点钟位置 ,结束角 通过改变 step 的值确定
context.arc(40, 40, 30, -Math.PI / 2, step * Math.PI - Math.PI / 2, false);
context.stroke();
context.draw()
var ctx = wx.createCanvasContext('canvasProgressbg')
ctx.setLineWidth(8);// 设置圆环的宽度
ctx.setStrokeStyle('#eee'); // 设置圆环的颜色
ctx.setLineCap('round') // 设置圆环端点的形状
ctx.beginPath();//开始一个新的路径
ctx.arc(40,40,30, 0, 2 * Math.PI, false);
// 以下是数字居中
ctx.strokeStyle = '#eee'
ctx.lineWidth = 10
ctx.lineCap = 'butt' //butt平直 round圆 square方
// 设置文字居中但是fillText的第二个参数必须为画布宽度一半
ctx.textAlign = 'center'
ctx.font = 'bold 16px Arial'
ctx.fillStyle = '#666' //文本颜色
ctx.fillText(this.data.downTime, 40, 45) //fillText里面的可填写的值是,文本内容,x坐标,y坐标,文本最大宽度
ctx.font = '16px Arial'
ctx.fillStyle = '#FFFFFF'
ctx.stroke();//对当前路径进行描边
ctx.draw();
},
onShow: function () {
this.countInterval() //调用
},
2021.08.30