Vue2 实现图片的拖拽、缩放、旋转
在Vue 2中,可以使用原生JavaScript结合Vue的指令来实现图片的拖拽、缩放和旋转功能。以下是一个简单的示例:
<template>
<div id="app">
<div
class="draggable-image"
v-draggable="image"
v-scalable="image"
v-rotatable="image"
:style="imageStyle"
>
<img :src="image.src" alt="Draggable Image" />
</div>
</div>
</template>
<script>
export default {
data() {
return {
image: {
src: 'path_to_your_image.jpg',
x: 0,
y: 0,
width: 200,
height: 200,
scale: 1,
rotation: 0,
},
};
},
directives: {
draggable: {
bind(el, binding) {
let dragging = false;
el.onmousedown = (e) => {
dragging = true;
e.preventDefault();
const offsetX = e.clientX - el.getBoundingClientRect().left;
const offsetY = e.clientY - el.getBoundingClientRect().top;
document.onmousemove = (e) => {
if (dragging) {
binding.value.x = e.clientX - offsetX;
binding.value.y = e.clientY - offsetY;
}
};
};
document.onmouseup = () => {
dragging = false;
};
},
},
scalable: {
bind(el, binding) {
let scaling = false;
let startDist = 0;
el.onmousewheel = (e) => {
e.preventDefault();
const currentDist = e.wheelDelta ? e.wheelDelta : -e.deltaY;
if (currentDist > 0 && binding.value.scale > 0.3) {
binding.value.scale -= 0.05;
} else if (currentDist < 0 && binding.value.scale < 2) {
binding.value.scale += 0.05;
}
};
},
},
rotatable: {
bind(el, binding) {
let rotating = false;
let startDeg = 0;
el.onmousedown = (e) => {
rotating = true;
e.preventDefault();
startDeg = e.clientX - el.getBoundingClientRect().left - el.getBoundingClientRect().width / 2;
document.onmousemove = (e) => {
if (rotating) {
const currentDeg = e.clientX - el.getBoundingClientRect().left - el.getBoundingClientRect().width / 2;
bin
评论已关闭