vue实现印章拖拽效果
Vue 实现印章拖拽效果
核心思路
通过 Vue 的指令和事件绑定实现拖拽功能,结合 CSS 定位和 transform 属性完成视觉交互。需监听 mousedown、mousemove 和 mouseup 事件,动态计算元素位置。
实现步骤
1. 基础模板结构

<template>
<div class="stamp-container">
<div
class="stamp"
@mousedown="startDrag"
:style="{
left: stampPosition.x + 'px',
top: stampPosition.y + 'px',
transform: `rotate(${stampRotation}deg)`
}">
<!-- 印章内容(图片或文字) -->
<img src="stamp.png" alt="印章">
</div>
</div>
</template>
2. 数据与事件处理
<script>
export default {
data() {
return {
stampPosition: { x: 100, y: 100 }, // 初始位置
stampRotation: 0, // 旋转角度
isDragging: false,
startPos: { x: 0, y: 0 }
};
},
methods: {
startDrag(e) {
this.isDragging = true;
this.startPos = {
x: e.clientX - this.stampPosition.x,
y: e.clientY - this.stampPosition.y
};
document.addEventListener('mousemove', this.drag);
document.addEventListener('mouseup', this.stopDrag);
},
drag(e) {
if (!this.isDragging) return;
this.stampPosition = {
x: e.clientX - this.startPos.x,
y: e.clientY - this.startPos.y
};
},
stopDrag() {
this.isDragging = false;
document.removeEventListener('mousemove', this.drag);
document.removeEventListener('mouseup', this.stopDrag);
}
}
};
</script>
3. 样式优化

<style>
.stamp-container {
position: relative;
width: 100vw;
height: 100vh;
overflow: hidden;
}
.stamp {
position: absolute;
cursor: grab;
user-select: none;
width: 120px;
height: 120px;
}
.stamp:active {
cursor: grabbing;
}
</style>
进阶功能扩展
旋转控制
// 在 methods 中新增
rotateStamp() {
this.stampRotation = (this.stampRotation + 15) % 360;
}
边界限制
// 修改 drag 方法
drag(e) {
if (!this.isDragging) return;
const maxX = window.innerWidth - 120;
const maxY = window.innerHeight - 120;
this.stampPosition = {
x: Math.max(0, Math.min(e.clientX - this.startPos.x, maxX)),
y: Math.max(0, Math.min(e.clientY - this.startPos.y, maxY))
};
}
移动端适配
// 添加 touch 事件处理
startDrag(e) {
const clientX = e.type.includes('touch') ? e.touches[0].clientX : e.clientX;
const clientY = e.type.includes('touch') ? e.touches[0].clientY : e.clientY;
// 其余逻辑相同
}
性能优化建议
- 使用 CSS
will-change: transform提升渲染性能 - 节流
mousemove事件处理 - 对于复杂印章图形,建议使用 SVG 替代图片






