Vue3+Ts+Canvas封装电子签名组件
Canvas使用
canvas的简介,和SVG的区别,基本使用等等请参考Canvas的基本介绍与使用,图解+案例带你快速上手Canvas.
效果图
可以在PC端和移动端使用:
回显修改后:
父组件使用子组件
该组件使用的事父子组件传值
父组件引用子组件——一般放在最外层的components文件夹中
import Signature from '@/components/Signature/index.vue'
组件的使用——别着急,传递参数会在子组件中有清晰注释
<Signature
class="handover"
v-show="isHandover"
:width="300"
:height="300"
:echo="true"
ref="handoverRef"
@close="isHandover = false"
/>
敲黑板——子组件代码来了
创建Canvas
<template>
<div class="signature">
<canvas
ref="canvas"
class="signature_canvas"
:width="props.width"
:height="props.height"
:style="{ backgroundColor: props.bgColor }"
/>
<div
v-if="echo"
class="content-btn"
>
<el-button
link
@click="clear"
>
清除
</el-button>
<el-button
link
@click="closeContainer"
>
确定
</el-button>
</div>
</div>
</template>
引入vue中的方法
import {
ref, onMounted, onUnmounted, watch } from 'vue'
TS代码来啦
interface Props {
width?: any
height?: any
// 签名回显
img?: any
// 背景颜色
bgColor?: any
// 线条颜色
strokeStyle?: any
// 线条宽度
lineWidth?: any
// 回显模式
echo?: boolean
// 是否显示确定按钮
submitVisible?: boolean
}
// props 传递的参数 设置默认参数
const props: Props = defineProps({
width: {
type: Number,
default: 600
},
height: {
type: Number,
default: 100
},
bgColor: {
type: String,
default: '#FFFFFF'
},
img: {
type: String,
default: ''
},
echo: {
type: Boolean,
default: false
},
strokeStyle: {
type: String,
default: '#000000'
},
lineWidth: {
type: Number,
default: 2
},
submitVisible: {
type: Boolean,
default: true
}
})
// 使用ref创建一个对canvas元素的引用,初始值为null
const canvas = ref<HTMLCanvasElement | null>(null)
// 初始化CanvasRenderingContext2D上下文为null
// 这将在后续用于绘图操作
let ctx: CanvasRenderingContext2D | null = null
// 使用ref创建一个布尔值引用,用于跟踪绘图状态
// 初始值为false表示绘图尚未开始
const drawing = ref(false)
// 是否签名
let isSignature = false
/**
* 初始化最后触摸位置的x和y坐标
*/
const lastX = ref(0)
const lastY = ref(0)
/**
* 监视props.img的变化,当图像更新时重新绘制签名图像
*/
watch(
() => props.img,
value => {
drawSignImage(value)
}
)
/**
* 初始化画布配置。
*
* 该函数用于设置画布(canvas)的上下文(ctx)属性,包括线条颜色、填充颜色、线条连接方式和线条端点样式等。
* 如果画布不存在,则不进行任何操作。
*
* @returns {void}
*/
const initCanvas = () => {