<template>
<div>
角度:<input v-model="selectedAngle"></input><br>
<div>
<a-input-number
:default-value="100"
:min="0"
:max="100"
:formatter="value => `${value}%`"
:parser="value => value.replace('%', '')"
@change="onChange"
/>
</div>
<canvas ref="canvas" @mousemove="handleMouseMove" @click="handleClick"></canvas>
</div>
</template>
<script>
export default {
name:"AngleSelecd",
mounted() {
this.canvas = this.$refs.canvas;
this.context = this.canvas.getContext("2d");
this.selectedAngle = 0;
this.drawDashboard();
},
methods: {
onChange(value) {
console.log('changed', value);
this.value=value
this.selectedAngle=this.value
},
drawDashboard() {
const centerX = this.canvas.width / 2;
const centerY = this.canvas.height / 2;
const radius = Math.min(centerX, centerY) - 10;
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
// 绘制仪表盘背景
this.context.beginPath();
this.context.arc(centerX, centerY, radius, 0, 2 * Math.PI);
this.context.fillStyle = "lightgray";
this.context.fill();
// 绘制角度标记
this.context.font = "12px Arial";
this.context.fillStyle = "black";
this.context.textAlign = "center";
this.context.textBaseline = "middle";
for (let angle = 0; angle < 360; angle += 30) {
const angleRad = angle * (Math.PI / 180);
const markerX = centerX + (radius - 10) * Math.cos(angleRad);
const markerY = centerY - (radius - 10) * Math.sin(angleRad);
this.context.fillText(angle.toString(), markerX, markerY);
}
// 绘制指针
const angle = this.selectedAngle * (Math.PI / 180);
const pointerLength = radius * 0.8;
const pointerX = centerX + pointerLength * Math.cos(angle);
const pointerY = centerY - pointerLength * Math.sin(angle);
this.context.beginPath();
this.context.moveTo(centerX, centerY);
this.context.lineTo(pointerX, pointerY);
this.context.lineWidth = 2;
this.context.strokeStyle = "red";
this.context.stroke();
// 打印选中角度
this.context.font = "16px Arial";
this.context.fillStyle = "black";
this.context.fillText(`Selected Angle: ${this.selectedAngle}°`, 10, 20);
},
handleClick(event) {
this.updateSelectedAngle(event);
},
handleMouseMove(event) {
if (event.buttons === 1) {
this.updateSelectedAngle(event);
}
},
updateSelectedAngle(event) {
const rect = this.canvas.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
const centerX = this.canvas.width / 2;
const centerY = this.canvas.height / 2;
// 计算选中角度
const angle = Math.atan2(centerY - y, x - centerX);
let selectedAngle = (angle * 180) / Math.PI;
if (selectedAngle < 0) {
selectedAngle += 360;
}
this.selectedAngle = Math.round(selectedAngle);
this.increaseCounter()
this.drawDashboard();
},
increaseCounter() {
console.log("实时发送数据:",this.selectedAngle)
this.$emit("counter-updated", this.selectedAngle);
},
},
data() {
return {
timer:null,
canvas: null,
context: null,
selectedAngle: 0,
value:null
};
},
watch: {
selectedAngle(newValue) {
this.drawDashboard();
this.increaseCounter()
this.onChange(newValue)
},
}
};
</script>