<script lang="ts" setup name="CanvasIndex"> const canvasContext = ref(null) as any // Canvas上下文对象 const isDrawing = ref(false) // 标记当前是否正在画图 const lastX = ref(0) // 鼠标最后点击位置的x坐标 const lastY = ref(0) // 鼠标最后点击位置的y坐标 const canvasRef = ref() // 组件ref function initCanvas() { const canvas = canvasRef.value canvasContext.value = canvas.getContext('2d') // 设置Canvas大小与容器相同 canvas.width = canvas.parentNode.offsetWidth canvas.height = canvas.parentNode.offsetHeight // 添加事件监听 canvas.addEventListener('mousemove', draw()) canvas.addEventListener('mouseup', () => (isDrawing.value = false)) } function startDrawing(event: any) { if (!isDrawing.value) { lastX.value = event.clientX - canvasRef.value.offsetLeft lastY.value = event.clientY - canvasRef.value.offsetTop isDrawing.value = true } } function draw(event?: any) { if (isDrawing.value) { const currentX = event.clientX - canvasRef.value.offsetLeft const currentY = event.clientY - canvasRef.value.offsetTop canvasContext.value!.beginPath() canvasContext.value!.moveTo(lastX.value, lastY.value) canvasContext.value!.lineTo(currentX, currentY) canvasContext.value!.strokeStyle = 'black' canvasContext.value!.lineWidth = 5 canvasContext.value!.stroke() lastX.value = currentX lastY.value = currentY } } function clear() { canvasContext.value.clearRect(0, 0, canvasRef.value.width, canvasRef.value.height) } onMounted(() => { initCanvas() }) </script> <template> <div class="signature-container"> <canvas ref="canvasRef" @mousedown="startDrawing" /> <button @click="clear"> 清除 </button> </div> </template> <style scoped> .signature-container { position: relative; } canvas { border: 1px solid #ccc; } button { position: absolute; top: 10px; right: 10px; } </style>