Vue 可拖拽缩放背景图片组件 - 使用 vue-draggable-resizable 和 vue2-touch-events
<p>本文提供一个简单的代码示例,使用 vue-draggable-resizable 和 vue2-touch-events 插件来实现一个可拖拽缩放的背景图片组件,支持鼠标和触控操作。</p>
<template>
<div class='container'>
<vue-draggable-resizable
:w='width'
:h='height'
:x='left'
:y='top'
:z='1'
:min-w='100'
:min-h='100'
:parent='true'
:active='true'
:drag-handle='.drag-handle'
:resizable='{
top: true,
right: true,
bottom: true,
left: true,
topRight: true,
bottomRight: true,
bottomLeft: true,
topLeft: true
}'
@dragging='onDragging'
@resizing='onResizing'
>
<div class='drag-handle'>
<img :src='imageUrl' />
</div>
</vue-draggable-resizable>
</div>
</template>
<script>
import VueDraggableResizable from 'vue-draggable-resizable';
import 'vue-draggable-resizable/dist/VueDraggableResizable.css';
import Vue2TouchEvents from 'vue2-touch-events';
export default {
name: 'DraggableImage',
components: {
VueDraggableResizable
},
directives: {
touch: Vue2TouchEvents
},
data() {
return {
imageUrl: '', // 背景图片地址
width: 400, // 图片宽度
height: 400, // 图片高度
left: 0, // 图片距离左边界距离
top: 0, // 图片距离上边界距离
scale: 1, // 图片缩放比例
startX: 0, // 开始拖拽时的x坐标
startY: 0 // 开始拖拽时的y坐标
};
},
methods: {
onDragging() {
this.left = this.$refs.draggable.x;
this.top = this.$refs.draggable.y;
},
onResizing() {
this.width = this.$refs.draggable.w;
this.height = this.$refs.draggable.h;
},
onTouchStart(e) {
this.startX = e.changedTouches[0].clientX;
this.startY = e.changedTouches[0].clientY;
},
onTouchMove(e) {
const offsetX = e.changedTouches[0].clientX - this.startX;
const offsetY = e.changedTouches[0].clientY - this.startY;
this.left += offsetX;
this.top += offsetY;
this.startX = e.changedTouches[0].clientX;
this.startY = e.changedTouches[0].clientY;
},
onTouchScale(e) {
this.scale *= e.scale;
this.width *= e.scale;
this.height *= e.scale;
this.left -= (this.width - this.width / e.scale) / 2;
this.top -= (this.height - this.height / e.scale) / 2;
}
}
};
</script>
<style scoped>
.container {
position: relative;
width: 100%;
height: 100%;
}
.drag-handle {
width: 100%;
height: 100%;
cursor: move;
}
.drag-handle img {
width: 100%;
height: 100%;
object-fit: cover;
}
</style>
<p>在父组件中引入 DraggableImage 组件,并传入背景图片地址:</p>
<template>
<div class='parent'>
<DraggableImage :imageUrl='imageUrl' />
</div>
</template>
<script>
import DraggableImage from './DraggableImage.vue';
export default {
name: 'App',
components: {
DraggableImage
},
data() {
return {
imageUrl: 'https://picsum.photos/id/237/800/800' // 背景图片地址
};
}
};
</script>
原文地址: https://www.cveoy.top/t/topic/lXsT 著作权归作者所有。请勿转载和采集!