项目中有时候会遇到画圆来形象地显示占比或者进度,在页面mounted的时候就请求数据,然后画图,先看成品
代码如下:
vue:
{{item.value}}
{{item.name}}
js:
circleDataMax:100,
circleData: [
{name: '全部设备', param: 'size', value: 0, max: 100, color: '#1964fb'},
{name: '在线设备', param: 'onlineNum', value: 0, max: 100, color: '#5ab486'},
{name: '离线设备', param: 'offlineNum', value: 0, max: 100, color: '#a7adc8'},
{name: '累计违章', param: 'cumulativeViolation', value: 0, max: 100, color: '#fb5f57'},
{name: '累计报警', param: 'cumulativeAlarm', value: 0, max: 100, color: '#ff605f'},
],
async getDetailData(){
let res = await crane.getDetailData()
if(res?.code===200){
detail.circleData.forEach((item,index)=>{
item.value=res.data[item.param] || 0
item.max=detail.circleDataMax
})
detail.drawCircle()
}
},
drawCircle() {
detail.circleData.forEach(item => {
detail.draw(item)
})
},
draw(item) {
let WIDTH = 140, HEIGHT = 140, R1 = 60, R2 = 50, lineWidth = 10;
let sAngle = -90 * Math.PI / 180;//开始位置
let eAngle = (-90 - 360 * item.value / item.max) * Math.PI / 180;//结束位置
let canvas = document.getElementById(item.param)
canvas.width = WIDTH;
canvas.height = HEIGHT;
if (canvas) {
let ctx = canvas.getContext('2d');
ctx.strokeStyle = '#59658c';
ctx.beginPath();
ctx.arc(WIDTH / 2, HEIGHT / 2, R1, 0, Math.PI * 2);
ctx.lineWidth = lineWidth;
ctx.stroke()
ctx.closePath()
if(item.value!=0){//如果0应该不显示
ctx.strokeStyle = item.color;
ctx.beginPath();
ctx.arc(WIDTH / 2, HEIGHT / 2, R1, sAngle, eAngle, true);
ctx.lineWidth = lineWidth;
ctx.lineCap = 'round';
}
ctx.stroke()
ctx.closePath()
}
}
style:
.circle-wrapper {
display: flex;
justify-content: space-around;
.circle-item {
width: 139px;
height: 139px;
border: 5px solid transparent;
position: relative;
.circle-info {
width: 100px;
height: 100px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
color: #fff;
position: absolute;
top:50%;
left:50%;
margin-top:-50px;
margin-left:-50px;
}
canvas{
position: absolute;
top:50%;
left:50%;
margin-top:-70px;
margin-left:-70px;
}
}
}