<template>
<div>
<canvas ref="canvas" @mousedown="onMouseDown" @mouseup="onMouseUp" @mousemove="onMouseMove"></canvas>
</div>
</template>
<script>
export default {
data() {
return {
canvas: null,
ctx: null,
isDragging: false,
ctrlKey: false,
startX: 0,
startY: 0,
endX: 0,
endY: 0,
radius: 20,
};
},
mounted() {
this.canvas = this.$refs.canvas;
this.ctx = this.canvas.getContext('2d');
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
this.ctx.fillStyle = 'rgba(255,255,255,0.8)';
this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
},
methods: {
// 按下鼠标左键事件
onMouseDown(event) {
this.startX = event.clientX;
this.startY = event.clientY;
this.isDragging = true;
// 判断是否按住Ctrl键
this.ctrlKey = event.ctrlKey;
},
// 松开鼠标左键事件
onMouseUp(event) {
this.endX = event.clientX;
this.endY = event.clientY;
if (this.isDragging) {
// 如果按住Ctrl键,则绘制圆形
if (this.ctrlKey) {
this.drawCircle();
}
}
this.isDragging = false;
},
// 移动鼠标事件
onMouseMove(event) {
if (this.isDragging) {
// 如果按住Ctrl键,则绘制临时圆形
if (this.ctrlKey) {
this.drawTempCircle(event.clientX, event.clientY);
}
}
},
// 绘制圆形
drawCircle() {
const x = (this.startX + this.endX) / 2;
const y = (this.startY + this.endY) / 2;
this.ctx.beginPath();
this.ctx.arc(x, y, this.radius, 0, 2 * Math.PI);
this.ctx.fillStyle = '#ff0000';
this.ctx.fill();
},
// 绘制临时圆形
drawTempCircle(x, y) {
this.ctx.fillStyle = 'rgba(255,255,255,0.8)';
this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
this.ctx.beginPath();
this.ctx.arc(x, y, this.radius, 0, 2 * Math.PI);
this.ctx.fillStyle = '#ff0000';
this.ctx.fill();
},
},
};
</script>
该示例代码使用Vue的单文件组件格式,包含一个canvas元素和对应的事件监听器和方法。在鼠标事件中,通过判断是否按住Ctrl键来绘制圆形或临时圆形,绘制时使用canvas的API来进行。