创建一个progress-circle.vue文件
<template>
<div>
<canvas
:canvas-id="'progress' + id"
:style="{ width: size + 'rpx', height: size + 'rpx' }"
></canvas>
<slot></slot>
</div>
</template>
<script>
export default {
props: ["id", "percent", "progressColor"],
data() {
return {
sizeNum: this.size, //最终的整体尺寸
strokeWidthNum: this.strokeWidth, //最终的轨道宽度数值,
bgColor: "#F0F3FA",
timeBgColor: "#e39214",
size: 125,
strokeWidth: 10,
};
},
mounted() {
this.$cu.log("canvas");
this.drawProgress();
// this.drawTimeProgress();
},
methods: {
drawProgress() {
//尺寸与轨道宽度自适应处理
const screenWidth = uni.getSystemInfoSync().screenWidth;
this.sizeNum = (this.size / 750) * screenWidth;
this.strokeWidthNum = (this.strokeWidth / 750) * screenWidth;
const ctx = uni.createCanvasContext(`progress${this.id}`, this);
const centerX = this.sizeNum / 2;
const centerY = this.sizeNum / 2;
const radius = (this.sizeNum - this.strokeWidthNum) / 2;
const startAngle = 1.5 * Math.PI;
const endAngle = startAngle - (this.percent / 100) * 2 * Math.PI;
// 绘制背景圆
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
ctx.setFillStyle("#FFFFFF");
ctx.fill();
// 绘制轨道圆环
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
ctx.setLineWidth(this.strokeWidthNum);
ctx.setStrokeStyle(this.bgColor);
ctx.setLineCap("round");
ctx.stroke();
// 绘制进度圆环
ctx.beginPath();
ctx.arc(centerX, centerY, radius, startAngle, endAngle, true);
ctx.setLineWidth(this.strokeWidthNum);
ctx.setStrokeStyle(this.progressColor);
ctx.setLineCap("round");
ctx.stroke();
ctx.draw(true);
},
drawTimeProgress() {
//尺寸与轨道宽度自适应处理
const screenWidth = uni.getSystemInfoSync().screenWidth;
this.sizeNum = (this.size / 750) * screenWidth;
this.strokeWidthNum = (this.strokeWidth / 750) * screenWidth;
const ctx = uni.createCanvasContext(`progress${this.id}`, this);
const centerX = this.sizeNum / 2;
const centerY = this.sizeNum / 2;
const radius = (this.sizeNum - this.strokeWidthNum) / 2;
const startAngle = 1.5 * Math.PI;
const endAngle = startAngle - (this.percent / 100) * 2 * Math.PI;
// 绘制轨道圆环
ctx.beginPath();
ctx.arc(centerX, centerY, radius - 12, 0, 2 * Math.PI);
ctx.setLineWidth(this.strokeWidthNum);
ctx.setStrokeStyle(this.timeBgColor);
ctx.setLineCap("round");
ctx.stroke();
// 绘制进度圆环
ctx.beginPath();
ctx.arc(centerX, centerY, radius - 12, startAngle, endAngle, true);
ctx.setLineWidth(this.strokeWidthNum);
ctx.setStrokeStyle(this.timeBgColor);
ctx.setLineCap("round");
ctx.stroke();
ctx.draw(true);
},
},
watch: {
percent: {
handler() {
this.drawProgress();
// this.drawTimeProgress();
},
},
},
};
</script>
在其他页面使用
<progressCircle
:percent="percent"
:progressColor="col"
:id="id"
>
<div class="content">
<!-- 插槽位置放置需要的内容 -->
</div>
</progressCircle>