vue实现盖章
Vue 实现盖章功能
在 Vue 中实现盖章功能通常涉及以下几个关键步骤:绘制印章、处理交互逻辑、保存盖章结果。以下是具体实现方法:

绘制印章
使用 Canvas 或 SVG 绘制印章图形,Vue 中可以封装为组件。

<template>
<canvas ref="stampCanvas" @click="handleStamp"></canvas>
</template>
<script>
export default {
methods: {
drawStamp() {
const canvas = this.$refs.stampCanvas;
const ctx = canvas.getContext('2d');
// 绘制圆形印章
ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI * 2);
ctx.strokeStyle = 'red';
ctx.lineWidth = 3;
ctx.stroke();
// 添加文字
ctx.font = '16px Arial';
ctx.fillStyle = 'red';
ctx.fillText('专用章', 70, 100);
}
},
mounted() {
this.drawStamp();
}
};
</script>
交互逻辑
通过事件监听实现点击或拖拽盖章效果。
<template>
<div @click="placeStamp" style="position: relative;">
<img src="document.jpg" alt="文档">
<div v-if="stampVisible" :style="stampStyle">
<svg width="100" height="100" viewBox="0 0 100 100">
<circle cx="50" cy="50" r="45" stroke="red" stroke-width="2" fill="none"/>
<text x="50" y="50" text-anchor="middle" fill="red">盖章</text>
</svg>
</div>
</div>
</template>
<script>
export default {
data() {
return {
stampVisible: false,
stampPosition: { x: 0, y: 0 }
};
},
computed: {
stampStyle() {
return {
position: 'absolute',
left: `${this.stampPosition.x}px`,
top: `${this.stampPosition.y}px`,
pointerEvents: 'none'
};
}
},
methods: {
placeStamp(e) {
this.stampPosition = { x: e.offsetX - 50, y: e.offsetY - 50 };
this.stampVisible = true;
}
}
};
</script>
保存盖章结果
将盖章后的内容导出为图片或提交到后端。
methods: {
saveWithStamp() {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// 绘制文档背景
const img = new Image();
img.onload = () => {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
// 叠加印章
const stamp = new Image();
stamp.onload = () => {
ctx.drawImage(stamp, this.stampPosition.x, this.stampPosition.y);
const dataURL = canvas.toDataURL('image/png');
// 保存或上传
console.log(dataURL);
};
stamp.src = 'stamp.svg';
};
img.src = 'document.jpg';
}
}
进阶优化
- 动态印章:通过
v-for实现多个印章位置记录。 - 拖拽调整:使用
@mousedown和@mousemove实现印章位置拖拽。 - 透明度控制:通过 CSS
opacity或 CanvasglobalAlpha调整印章透明度。
<div
v-for="(stamp, index) in stamps"
:key="index"
:style="getStampStyle(stamp)"
@mousedown="startDrag(index, $event)"
>
<svg>...</svg>
</div>
通过以上方法,可以在 Vue 中灵活实现盖章功能,并根据需求扩展交互细节。






