vue实现盖章
Vue 实现盖章功能
在Vue中实现盖章功能通常涉及前端UI交互,通过Canvas或SVG绘制印章,并允许用户拖拽或点击放置印章。以下是具体实现方法:
使用Canvas绘制印章
通过HTML5的Canvas动态绘制印章图形,结合Vue的数据绑定实现交互。
模板部分:
<template>
<div>
<canvas ref="stampCanvas" width="200" height="200"></canvas>
<button @click="placeStamp">盖章</button>
</div>
</template>
脚本部分:
<script>
export default {
methods: {
drawStamp() {
const canvas = this.$refs.stampCanvas;
const ctx = canvas.getContext('2d');
// 绘制圆形印章
ctx.beginPath();
ctx.arc(100, 100, 80, 0, 2 * Math.PI);
ctx.strokeStyle = 'red';
ctx.lineWidth = 3;
ctx.stroke();
// 绘制文字
ctx.font = '16px Arial';
ctx.fillStyle = 'red';
ctx.textAlign = 'center';
ctx.fillText('专用章', 100, 100);
},
placeStamp() {
this.drawStamp();
}
},
mounted() {
this.drawStamp();
}
};
</script>
使用SVG实现可拖拽印章
通过SVG实现矢量印章,并添加拖拽功能。
模板部分:
<template>
<div>
<svg width="300" height="300" @mousedown="startDrag" @mousemove="drag" @mouseup="endDrag">
<circle cx="150" cy="150" r="80" stroke="red" stroke-width="3" fill="none" />
<text x="150" y="150" text-anchor="middle" fill="red">专用章</text>
</svg>
</div>
</template>
脚本部分:
<script>
export default {
data() {
return {
isDragging: false,
offsetX: 0,
offsetY: 0
};
},
methods: {
startDrag(e) {
this.isDragging = true;
this.offsetX = e.clientX - e.target.getBoundingClientRect().left;
this.offsetY = e.clientY - e.target.getBoundingClientRect().top;
},
drag(e) {
if (this.isDragging) {
const svg = e.target;
svg.style.position = 'absolute';
svg.style.left = `${e.clientX - this.offsetX}px`;
svg.style.top = `${e.clientY - this.offsetY}px`;
}
},
endDrag() {
this.isDragging = false;
}
}
};
</script>
结合第三方库
使用如fabric.js等库实现更复杂的盖章交互:
-
安装依赖:
npm install fabric -
实现代码:
<template> <canvas ref="canvas" width="500" height="500"></canvas> </template>
export default { mounted() { const canvas = new fabric.Canvas(this.$refs.canvas);
// 创建印章对象
const stamp = new fabric.Circle({
radius: 50,
fill: 'transparent',
stroke: 'red',
strokeWidth: 3,
left: 100,
top: 100,
hasControls: false // 禁止缩放
});
// 添加文字
const text = new fabric.Text('公章', {
left: 80,
top: 95,
fontSize: 16,
fill: 'red'
});
// 组合为印章
const group = new fabric.Group([stamp, text], {
hasControls: false,
lockRotation: true
});
canvas.add(group);
// 拖拽交互
canvas.on('mouse:down', (opt) => {
if (opt.target === group) {
canvas.setActiveObject(group);
}
});
} };
```注意事项
- 性能优化:频繁操作Canvas时需注意重绘性能,避免不必要的渲染。
- 移动端适配:若需支持移动端,需替换鼠标事件为触摸事件(如
touchstart、touchmove)。 - 保存状态:若需保存盖章后的结果,可通过
canvas.toDataURL()导出为图片。
以上方法可根据实际需求选择,Canvas适合动态生成,SVG适合矢量缩放,第三方库(如fabric.js)提供更完整的交互功能。







