xiaohantx
194 天前
```
const drawCanvas = (canvasId, data) => {
uni.createSelectorQuery().select(canvasId).fields({
node: true,
size: true
}).exec(res => {
// 处理数据
demoList[0].value = data.levelOne ?? 0
demoList[1].value = data.levelTwo ?? 0
demoList[2].value = data.levelThree ?? 0
const {
devicePixelRatio,
screenWidth
} = uni.getSystemInfoSync()
const rpx = devicePixelRatio
const canvas = res[0].node
let ctx = canvas.getContext('2d')
// 初始化画布大小
canvas.width = res[0].width * rpx
canvas.height = res[0].height * rpx
// 获取结束
const x = res[0].width / 2 * rpx;
const y = res[0].height / 2 * rpx;
const lineWidth = 20 * rpx;
const radius = (res[0].height / 2) * rpx - (lineWidth / 2) // 半径
const sumResult = canvasId === '#chart' ? data.errorTotal : data.alertTotal;
let startAngle = 0;
demoList.map(item => {
// 绘制数组中的百分比
ctx.beginPath();
console.log('sum', sumResult)
let angle = (item.value / sumResult) * 2 * Math.PI
ctx.arc(x, y, radius, startAngle, startAngle + angle);
ctx.lineWidth = lineWidth;
ctx.strokeStyle = item.color;
ctx.stroke();
startAngle += angle
})
// 文字颜色
ctx.fillStyle = "#1D2129"
ctx.font = `${30 * rpx}px sans-serif`
ctx.textAlign = 'center'
// // 文字位置
// // 插入文字
ctx.fillText(sumResult, canvas.width / 2, y)
// // 文字大小
ctx.fillStyle = "#86909C"
ctx.font = `${12 * rpx}px sans-serif`
ctx.textAlign = 'center'
// // 文字颜色
// // 插入文字
ctx.fillText('故障总计(台)', canvas.width / 2, y + (20 * rpx))
uni.canvasToTempFilePath({
canvas: canvas,
success: function(res) {
if (canvasId === '#chart') {
canvasSrc1.value = res.tempFilePath;
} else {
canvasSrc2.value = res.tempFilePath;
}
},
fail: function(res) {
console.log(222, res)
}
})
})
}
```