vue3 语法 实现 canvas 签名
时间: 2023-12-06 08:57:45 浏览: 146
vue+canvas实现移动端手写签名
5星 · 资源好评率100%
好的,下面是一个简单的 Vue3 组件,可以用来实现 Canvas 签名:
```html
<template>
<div>
<canvas ref="canvas" @mousedown="startDrawing" @mousemove="draw" @mouseup="finishDrawing"></canvas>
<button @click="clear">Clear</button>
</div>
</template>
<script>
import { onMounted, ref } from 'vue'
export default {
setup() {
const canvasRef = ref(null)
const isDrawing = ref(false)
let x = 0
let y = 0
const startDrawing = (event) => {
x = event.offsetX
y = event.offsetY
isDrawing.value = true
}
const draw = (event) => {
if (!isDrawing.value) return
const canvas = canvasRef.value
const context = canvas.getContext('2d')
context.beginPath()
context.moveTo(x, y)
context.lineTo(event.offsetX, event.offsetY)
context.stroke()
x = event.offsetX
y = event.offsetY
}
const finishDrawing = () => {
isDrawing.value = false
}
const clear = () => {
const canvas = canvasRef.value
const context = canvas.getContext('2d')
context.clearRect(0, 0, canvas.width, canvas.height)
}
onMounted(() => {
const canvas = canvasRef.value
const context = canvas.getContext('2d')
canvas.width = 300
canvas.height = 200
context.strokeStyle = 'black'
context.lineWidth = 2
})
return {
canvasRef,
startDrawing,
draw,
finishDrawing,
clear
}
}
}
</script>
```
这个组件包含一个 Canvas 元素和一个 Clear 按钮。当用户在 Canvas 上按下鼠标左键时,组件会开始绘制用户的签名。用户可以在 Canvas 上拖动鼠标来绘制他们的签名。当用户松开鼠标左键时,组件会停止绘制签名。当用户点击 Clear 按钮时,组件会清除 Canvas 上的所有内容。
这个组件使用了 Vue3 的 Composition API。它使用了 ref 函数来创建响应式变量,以及 onMounted 函数来在组件挂载时初始化 Canvas。
阅读全文