<template>
<canvas ref="canvas" id="canvas" width="600" height="500" class="pink"></canvas>
<el-button type="primary" @click="savePath">保存</el-button>
</template>
<script setup>
import {ref,onMounted} from 'vue'
const canvas = ref(null)
let ctx = null
let isDown = false
onMounted(()=>{
init()
})
const init = () => {
ctx = canvas.value.getContext('2d')
ctx.lineWidth = 2; //直线的宽度状态设置
ctx.fillStyle = "#ccc"; //直线的颜色状态设置
ctx.strokeStyle = "#000"; //直线的颜色状态设置
ctx.lineCap = 'round';
ctx.fillRect(0, 0, 600, 500);
draw()
}
const draw = () => {
canvas.value.addEventListener('mousedown', (e) => {
isDown = true
ctx.beginPath()
ctx.moveTo(e.offsetX, e.offsetY);
})
canvas.value.addEventListener('mousemove', (e) => {
if (isDown) {
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke()
}
})
document.documentElement.addEventListener('mouseup', (e) => {
isDown = false
})
}
const savePath = () => {
const url = canvas.value.toDataURL("image/png")
const a = document.createElement('a')
document.body.appendChild(a)
a.href = url
a.download = 'canvas'
a.click()
}
</script>
<style lang="scss" scoped>
.pink{
background-color: pink;
margin-top:10px
}
</style>
vue3实现手写签名并且保存到本地
于 2024-04-15 17:40:46 首次发布