uniapp手写圆环图
时间: 2023-09-20 09:08:54 浏览: 118
以下是uniapp手写圆环图的示例代码:
```html
<!-- template -->
<template>
<canvas style="width: 100%; height: 100%;" @canvasId="onCanvasInit"></canvas>
</template>
<!-- script -->
<script>
export default {
data() {
return {
canvasWidth: 0, // canvas 宽度
canvasHeight: 0, // canvas 高度
canvasId: '', // canvas id
canvasCtx: null, // canvas 上下文
percent: 50, // 百分比
lineWidth: 10, // 线宽度
lineColor: '#42b983', // 线颜色
lineBgColor: '#eee', // 线背景颜色
fontColor: '#666', // 字体颜色
fontSize: 24, // 字体大小
};
},
mounted() {
this.canvasId = 'myCanvas';
},
methods: {
// 初始化 canvas
onCanvasInit(id) {
const query = uni.createSelectorQuery().in(this);
query
.select(`#${id}`)
.fields({ node: true, size: true })
.exec((res) => {
const canvas = res[0].node;
const ctx = canvas.getContext('2d');
const dpr = uni.getSystemInfoSync().pixelRatio;
canvas.width = res[0].width * dpr;
canvas.height = res[0].height * dpr;
ctx.scale(dpr, dpr);
this.canvasWidth = canvas.width;
this.canvasHeight = canvas.height;
this.canvasCtx = ctx;
this.drawCircle();
});
},
// 绘制圆环
drawCircle() {
const ctx = this.canvasCtx;
const canvasWidth = this.canvasWidth;
const canvasHeight = this.canvasHeight;
const lineWidth = this.lineWidth;
const lineColor = this.lineColor;
const lineBgColor = this.lineBgColor;
const fontColor = this.fontColor;
const fontSize = this.fontSize;
const percent = this.percent;
const radius = Math.min(canvasWidth, canvasHeight) / 2 - lineWidth / 2;
const centerX = canvasWidth / 2;
const centerY = canvasHeight / 2;
// 绘制背景圆环
ctx.beginPath();
ctx.lineWidth = lineWidth;
ctx.strokeStyle = lineBgColor;
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
ctx.stroke();
// 绘制进度圆环
ctx.beginPath();
ctx.lineWidth = lineWidth;
ctx.strokeStyle = lineColor;
ctx.arc(
centerX,
centerY,
radius,
-0.5 * Math.PI,
(percent / 100) * 2 * Math.PI - 0.5 * Math.PI,
);
ctx.stroke();
// 绘制百分比文字
ctx.fillStyle = fontColor;
ctx.font = `${fontSize}px Arial`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(`${percent}%`, centerX, centerY);
},
},
};
</script>
```
使用示例:
```html
<template>
<view>
<my-circle />
</view>
</template>
<script>
import MyCircle from '@/components/MyCircle.vue';
export default {
components: {
MyCircle,
},
};
</script>
```
效果如下:
![圆环图](https://cdn.jsdelivr.net/gh/yuuFen/-/images/202112012200341.png)
阅读全文