微信小程序使用canvas实现应该圆形倒计时

0 阅读1分钟

image.png

实现这个效果,要大致判断使用canvas怎么布局 或者底图使用图片与canvas贴合

<view class="flex">
    <canvas canvas-id="canvasProgressbg" style="width:128rpx;height:128rpx;position: absolute;"></canvas>
    <canvas canvas-id="canvasProgress" style="width:128rpx;height:128rpx;"></canvas>
</view>

设计倒计时

countInterval(remainingRatio) {
    // 设置倒计时 定时器 每100毫秒执行一次,计数器count+1 ,耗时6秒绘一圈
    clearInterval(this.countTimer)
    this.countTimer = setInterval(() => {
        if (this.count <= 30) {
        // 绘制彩色圆环进度条  注意此处 传参 step 取值范围是0到2,
        //所以计数器最大值60对应2做处理,计数器count=60的时候step=2 

        // 计算剩余比例 (1-0)
        这块是通过逆时针减少
        remainingRatio = 1 - (this.count / this.totalTime);
        //顺时针
        // this.drawCircle(this.count / (30 / 2))
        this.drawCircle(remainingRatio)
        this.count++;
        this.downTime = this.totalTime - this.count;
       } else {   
       clearInterval(this.countTimer)
        wx.showToast({
            title: '时间到',
        })
       }
    }, 1000)
},

创建两个圆形

//环的变化
drawCircle(step) {
    // 背景圆环(固定灰色底)
    const bgCtx = wx.createCanvasContext('canvasProgressbg', this);
    bgCtx.setLineWidth(6);
    bgCtx.setStrokeStyle('rgba(255, 255, 255, 0.3)');
    bgCtx.setLineCap('round');
    bgCtx.beginPath();
    //x,y坐标自己微调
    bgCtx.arc(this.centerX, this.centerY, 25, 0, 2 * Math.PI);
    bgCtx.stroke();
    bgCtx.draw();

    // 进度圆环(随时间减少)
    const progressCtx = wx.createCanvasContext('canvasProgress', this);
    progressCtx.setLineWidth(6);
    progressCtx.setStrokeStyle('#FFFFFF');
    progressCtx.setLineCap('round');
    progressCtx.beginPath();

    // 计算结束角度,remainingRatio=1时为完整圆环,=0时为0度
    const endAngle = 2 * Math.PI * step;
    progressCtx.arc(this.centerX, this.centerY, 25, -Math.PI / 2, endAngle - Math.PI / 2);
    progressCtx.stroke();

    // 绘制剩余秒数
    progressCtx.setFontSize(parseInt(35 / this.dpr));
    progressCtx.setTextAlign('center');
    progressCtx.setTextBaseline('middle');
    progressCtx.setFillStyle('#FFFFFF');
    progressCtx.fillText(this.time, this.centerX,this.centerY);
    progressCtx.draw();
},

最终效果

image.png