vue3实现轮播渲染多张图每张进行放大缩小拖拽功能互不影响
1.以vue3中el-carousel轮播插件为例
<div class="pic_view"><el-carousel height="100vh" :autoplay="false" ref="carouselRef" @change="handleCarouselChange"><el-carousel-item v-for="item in picLists" :key="item.id" :data-id="item.id"><div :style="{ backgroundColor: item.backgroundColor }" @wheel.prevent="rollImg" class="pic_set":data-id="item.id" ref="picSetRefs"><img :src="getUrl(`${item.url}`)" class="img" @mousedown="startMove($event, item.id)" :style="{left: imgStates[item.id]?.position.x || '25%',top: imgStates[item.id]?.position.y || '0',transform: `scale(${imgStates[item.id]?.zoom || 1})`}" /></div></el-carousel-item></el-carousel></div>
注意:getUrl方法是vite处理静态资源图片的,由于是本地为了测试,你们拿例子的时候注意点可以去掉这个方法放你们本地路径渲染
2.事件
<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { getImageUrl } from '@/utils/pub-use'const getUrl = getImageUrlconst picLists = reactive([{ id: 1, url: 'yu1.webp', backgroundColor: '#6f6865' },{ id: 2, url: 'yu2.webp', backgroundColor: '#726A67' },{ id: 3, url: 'yu3.webp', backgroundColor: '#705947' },
])// 存储每个图片的状态
const imgStates = reactive({})
const picSetRefs = ref([])
let currentImgId = ref(null)
let isDragging = false
let startX = 0
let startY = 0
let currentImgElement = null
let currentImgRect = null
let initialOffsetX = 0
let initialOffsetY = 0
// yzm提示:由于一般方法只适用单张,特此整合渲染多张图操作
// 初始化图片状态
const initImgState = (id) => {if (!imgStates[id]) {imgStates[id] = {zoom: 0.8,position: { x: '25%', y: '0' },positionConverted: false}}
}// 将百分比位置转换为像素值
const convertPositionToPixels = (id, element) => {const state = imgStates[id]if (!state || state.positionConverted) returnconst parent = element.parentElementif (!parent) return// 转换水平位置if (typeof state.position.x === 'string' && state.position.x.includes('%')) {const percent = parseFloat(state.position.x)state.position.x = `${(percent / 100) * parent.clientWidth}px`}// 转换垂直位置if (typeof state.position.y === 'string' && state.position.y.includes('%')) {const percent = parseFloat(state.position.y)state.position.y = `${(percent / 100) * parent.clientHeight}px`}// 更新元素样式element.style.left = state.position.xelement.style.top = state.position.ystate.positionConverted = true
}// 轮播切换时更新当前图片ID
const handleCarouselChange = (currentIndex) => {currentImgId.value = picLists[currentIndex].id// 确保新激活的图片位置已转换nextTick(() => {const activeIndex = currentIndexif (picSetRefs.value[activeIndex]) {const img = picSetRefs.value[activeIndex].querySelector('.img')if (img) {convertPositionToPixels(picLists[activeIndex].id, img)}}})
}// 拖动图片相关函数
const startMove = (e, id) => {currentImgId.value = idinitImgState(id)currentImgElement = e.currentTarget// 确保位置已转换为像素值if (!imgStates[id].positionConverted) {convertPositionToPixels(id, currentImgElement)}e.preventDefault()isDragging = true// 获取当前图片的位置和尺寸currentImgRect = currentImgElement.getBoundingClientRect()// 计算初始位置(直接使用状态中的像素值)initialOffsetX = parseFloat(imgStates[id].position.x || '0')initialOffsetY = parseFloat(imgStates[id].position.y || '0')// 计算鼠标在图片中的位置startX = e.clientX - currentImgRect.leftstartY = e.clientY - currentImgRect.topdocument.addEventListener('mousemove', move)document.addEventListener('mouseup', stopMove)
}const move = (e) => {if (!isDragging || !currentImgId.value || !currentImgElement) return// 计算新的位置(考虑缩放)const zoom = imgStates[currentImgId.value].zoom || 1const newX = initialOffsetX + (e.clientX - currentImgRect.left - startX) / zoomconst newY = initialOffsetY + (e.clientY - currentImgRect.top - startY) / zoom// 更新位置imgStates[currentImgId.value].position = {x: `${newX}px`,y: `${newY}px`}currentImgElement.style.left = `${newX}px`currentImgElement.style.top = `${newY}px`
}const stopMove = () => {isDragging = falsecurrentImgElement = nulldocument.removeEventListener('mousemove', move)document.removeEventListener('mouseup', stopMove)
}// 缩放图片
const rollImg = (e) => {// 获取事件发生的轮播项IDconst itemId = parseInt(e.currentTarget.getAttribute('data-id'))if (itemId !== currentImgId.value) returninitImgState(itemId)// 获取当前操作的图片元素const img = e.currentTarget.querySelector('.img')if (!img) return// 确保位置已转换为像素值if (!imgStates[itemId].positionConverted) {convertPositionToPixels(itemId, img)}// 获取当前缩放值const transform = img.style.transform || ''let zoom = imgStates[itemId].zoomif (transform.includes('scale')) {const match = transform.match(/scale\(([\d.]+)\)/)if (match && match[1]) {zoom = parseFloat(match[1])}}// 根据滚轮方向调整缩放const delta = e.deltaY || e.wheelDeltaconst direction = delta > 0 ? -1 : 1zoom += direction * 0.1// 限制缩放范围zoom = Math.max(0.1, Math.min(zoom, 5))// 更新状态和样式imgStates[itemId].zoom = zoomimg.style.transform = `scale(${zoom})`e.preventDefault()
}// 组件卸载时清除事件
onBeforeUnmount(() => {stopMove()
})// 初始化所有图片状态
onMounted(() => {picLists.forEach(item => {initImgState(item.id)})// 设置初始当前图片IDif (picLists.length > 0) {currentImgId.value = picLists[0].id}nextTick(() => {if (picSetRefs.value[0]) {const img = picSetRefs.value[0].querySelector('.img')if (img) {convertPositionToPixels(picLists[0].id, img)}}})
})
</script>
我给每张图片设置不同背景,这个也要注意,不需要的话可以在HTML代码块里把背景操作去掉,geturl这个是我自己封装的工具文件,你们用不到这个可以删掉把图片地址弄对就行
样式
<style scoped lang="scss">
.pic_view {height: 100vh;overflow: hidden;:deep(.el-carousel) {height: 100%;.el-carousel__container {height: 100%;}.el-carousel__item {display: flex;justify-content: center;align-items: center;}}
}.pic_set {position: relative;width: 100%;height: 100%;overflow: hidden;display: flex;justify-content: center;align-items: center;touch-action: none;.img {position: absolute;height: 100%;max-width: 900px;min-height: 400px;margin-left: 2%;cursor: move;transform-origin: center center;transition: transform 0.1s ease;user-select: none;will-change: transform;}.imgLow {width: 100%;height: 80px;margin-top: 30vh;}
}
</style>
样式加了过度以及中心放大缩小,看更加丝滑
以上就是三块区域代码
效果