vue-esign 实现手签字添加背景文字
以下代码中实现了添加背景文字,重置,保存并展示手签字功能
<script setup lang="ts">
import { ElButton, ElCard, ElMessage } from 'element-plus'
import { ref, onMounted } from 'vue'
import vueEsign from 'vue-esign'
const esignRef = ref<ComponentRef<typeof vueEsign>>()
const resultImg = ref()
// 设置写字板背景颜色
const drawBackgroundText = () => {
const ctx: CanvasRenderingContext2D | null = esignRef.value.canvasTxt
if (!ctx) {
console.error('Canvas context not available.')
return
}
// 设置背景文字的样式
const fontSize = 30
ctx.font = `${fontSize}px Arial`
ctx.fillStyle = '#ccc' // 透明灰色背景文字
// 获取要绘制的背景文字
const backgroundText = '客户签名区'
// 将文字绘制在Canvas的中心位置
const textWidth = ctx.measureText(backgroundText).width
const canvasCenterX = esignRef.value.width / 2
const canvasCenterY = esignRef.value.height / 2
const textX = canvasCenterX - textWidth / 2
const textY = canvasCenterY + fontSize / 3
ctx.fillText(backgroundText, textX, textY)
}
// 清空画布
const resetEsign = () => {
esignRef.value.reset()
// 清除画布之后需要重新添加背景文字
drawBackgroundText()
}
onMounted(() => {
drawBackgroundText()
})
const mainLoading = ref(false)
// 保存
const handleSave = async () => {
esignRef.value
.generate()
.then((res) => {
console.log(res)
resultImg.value = res
})
.catch((e) => {
console.log(e)
return ElMessage.warning('请先在客户签字区签字!')
})
}
</script>
<template>
<div
ref="orderCardRef"
class="h-[100%] flex justify-center order-container"
v-loading="mainLoading"
>
<ElCard shadow="never" class="w-[900px] h-[100%]">
<div>
<div class="flex justify-between mb-1">
<h2 class="header-title">客户签名区</h2>
<div>
<ElButton type="danger" size="small" @click="handleSave">保存</ElButton>
<ElButton type="danger" size="small" @click="resetEsign">重写</ElButton>
</div>
</div>
<vueEsign
ref="esignRef"
class="border-dashed border-5"
height="200"
width="900"
:isCrop="false"
:isClearBgColor="false"
:lineWidth="6"
lineColor="#000000"
bgColor="#ffffff"
/>
<div class="esigh-result">
<img v-if="resultImg" :src="resultImg" alt="" />
</div>
</div>
</ElCard>
</div>
</template>
<style lang="less">
.order-container {
.el-card {
border: 0;
.el-card__body {
padding: 0;
.header-title {
line-height: 25px;
color: #333;
font-weight: 700;
font-size: 14px;
}
}
}
.esigh-result {
margin-top: 10px;
}
.esigh-result img {
display: block;
max-width: 100%;
height: auto;
border: 1px solid #ececee;
}
}
</style>