复制即用
<template>
<view class="container">
<canvas canvas-id="progress" class="progress"></canvas>
<view class="time">{{ time }}</view>
</view>
</template>
<script>
export default {
data() {
return {
time: 60,
//最好与下面圆环角度一致,更好的体验
timer: null,
ctx: null,
width: 0,
height: 0
}
},
onReady() {
this.ctx = uni.createCanvasContext('progress', this);
this.width = uni.upx2px(200);
this.height = uni.upx2px(200);
this.drawProgress(1);
this.startTimer();
},
methods: {
drawProgress(current) {
const ctx = this.ctx;
const r = this.width / 2;
const lineWidth = uni.upx2px(10);
ctx.clearRect(0, 0, this.width, this.height);
ctx.beginPath();
//最后一个参数,若为true,就是顺时针,为false,就是逆时针
ctx.arc(r, r, r - lineWidth, Math.PI * 1.5, current * Math.PI * 2 + Math.PI * 1.5, true);
ctx.setLineWidth(lineWidth);
ctx.setStrokeStyle('#4ccaff');
ctx.stroke();
ctx.draw();
},
startTimer() {
this.timer = setInterval(() => {
if (this.time <= 0) {
clearInterval(this.timer);
uni.showToast({
title: '倒计时结束',
icon: 'none'
});
return;
}
this.time--;
//这个修改圆环一秒为圆环多少度,60就是一个圆环360度减完为60秒
this.drawProgress(1 - this.time / 60);
}, 1000);
}
}
}
</script>
<style>
.container {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
height: 100vh;
background-color: #f5f5f5;
}
.progress {
width: 200upx;
height: 200upx;
background-color: #f0b0ff;
border-radius: 50%;
}
.time {
font-size: 36upx;
margin-top: 40upx;
color: #333333;
}
</style>