Vue3实现图片滚轮缩放和拖拽

2021-12-28 11:37:40 浏览数 (1)

代码语言:javascript复制
<template>
    <div ref="imgWrap" class="wrap" @mousewheel.prevent="rollImg">
        <img :src="url" alt ref="image" @mousedown.prevent="moveImg" />
    </div>
</template>
<script setup>
import { ref } from 'vue'
const url = ref("https://w.wallhaven.cc/full/8o/wallhaven-8oky1j.jpg")

const image = ref(null)
const rollImg = (e) => {
    let transform = image.value.style.transform
    let zoom = transform.indexOf("scale") != -1 ?  transform.split("(")[1].split(")")[0] : 1
    zoom  = e.wheelDelta / 1200
    if (zoom > 0.1 && zoom < 2) {
        image.value.style.transform = "scale("   zoom   ")"
    }
}

const imgWrap = ref(null)
const moveImg = (e) => {
    let wrap = imgWrap.value
    let img = image.value
    let x = e.pageX - img.offsetLeft
    let y = e.pageY - img.offsetTop
    // 添加鼠标移动事件
    wrap.addEventListener('mousemove', move)
    function move(e) {
        img.style.left = e.pageX - x   'px'
        img.style.top = e.pageY - y   'px'
    }
    // 添加鼠标抬起事件,鼠标抬起,将事件移除
    img.addEventListener('mouseup', () => {
        wrap.removeEventListener('mousemove', move)
    })
    // 鼠标离开父级元素,把事件移除
    wrap.addEventListener('mouseout', () => {
        wrap.removeEventListener('mousemove', move)
    })
}
</script>

<style lang='less' scoped>
.wrap {
    position: relative;
    width: 100vw;
    height: 100vh;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
}
img {
    position: absolute;
    cursor: move;
}
</style>

0 人点赞