纯JS+Vue和canvas实现一个仪表盘
<template>
<div>
<canvas ref="gaugeCanvas" width="200" height="200"></canvas>
</div>
</template>
<script>
export default {
name: 'Gauge',
props: {
value: {
type: Number,
default: 0
},
maxValue: {
type: Number,
default: 100
},
color: {
type: String,
default: '#42b983'
}
},
mounted() {
this.drawGauge(this.value);
},
watch: {
value(newValue) {
this.drawGauge(newValue);
}
},
methods: {
drawGauge(value) {
const canvas = this.$refs.gaugeCanvas;
const ctx = canvas.getContext('2d');
const radius = canvas.height / 2;
const startAngle = -0.5 * Math.PI;
const endAngle = 0.5 * Math.PI;
const counterClockwise = false;
// 清空画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制背景弧形
ctx.beginPath();
ctx.arc(radius, radius, radius, startAngle, endAngle, counterClockwise);
ctx.lineWidth = 10;
ctx.strokeStyle = '#e5e5e5';
ctx.stroke();
// 绘制当前值的弧形
const progressAngle = (value / this.maxValue) * Math.PI;
ctx.beginPath();
ctx.arc(radius, radius, radius, startAngle, progressAngle, counterClockwise);
ctx.lineWidth = 10;
ctx.strokeStyle = this.color;
ctx.stroke();
// 绘制中心点
ctx.beginPath();
ctx.arc(radius, radius, 5, 0, 2 * Math.PI);
ctx.fillStyle = this.color;
ctx.fill();
}
}
};
</script>
<style scoped>
canvas {
display: block;
margin: auto;
}
</style>
这段代码使用Vue和canvas创建了一个简单的仪表盘组件。它接受value
(当前值)、maxValue
(最大值)和color
(颜色)作为props。在mounted
钩子中,它会绘制初始仪表盘。使用watch
属性监听value
的变化,当值改变时重绘仪表盘以反映新的进度。这个例子展示了如何结合Vue和canvas实现数据驱动的可视化组件。
评论已关闭