vue实现 图片拖拽及鼠标滚轮放大缩小

效果:

代码实现

js 复制代码
<template>
  <div class="container">
    <div
      class="image-container"
      @mousewheel.stop="onMouseWheel"
      @mousedown="onMouseDown"
      @mousemove="onMouseMove"
      @mouseleave="onMouseLeave"
      @mouseup="onMouseUp"
    >
      <img :src="imageSrc" :style="{ transform: imageTransform }" ref="image" />
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      imageSrc:
        "https://img1.baidu.com/it/u=3065838285,2676115581&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1690995600&t=33317e67c6570c9f6d7cdfd53ee8db57",
      scale: 1,
      isDragging: false,
      dragStartX: 0,
      dragStartY: 0,
      imageLeft: 0,
      imageTop: 0,
    };
  },
  computed: {
    imageTransform() {
      return `translate(${this.imageLeft}px, ${this.imageTop}px) scale(${this.scale})`;
    },
  },
  methods: {
    onMouseWheel(event) {
      event.preventDefault();
      const wheelDelta = event.deltaY;
      if (wheelDelta > 0 && this.scale > 0.4) {
        this.scale -= 0.1;
      } else if (wheelDelta < 0) {
        this.scale += 0.1;
      }
    },
    onMouseDown(event) {
      this.isDragging = true;
      this.dragStartX = event.clientX;
      this.dragStartY = event.clientY;
      this.startImageX = this.imageLeft;
      this.startImageY = this.imageTop;
    },
    onMouseMove(event) {
      event.preventDefault();
      if (this.isDragging) {
        const offsetX = event.clientX - this.dragStartX;
        const offsetY = event.clientY - this.dragStartY;
        this.imageLeft = this.startImageX + offsetX;
        this.imageTop = this.startImageY + offsetY;
      }
    },
    onMouseUp() {
      this.isDragging = false;
    },
    onMouseLeave() {
      this.isDragging = false;
    },
  },
};
</script>

<style scoped>
.container {
  position: relative;
  width: 500px;
  height: 500px;
  border: 1px solid #ccc;
  overflow: hidden;
}
.image-container {
  position: absolute;
  top: 0;
  left: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
}
img {
  max-width: 100%;
  max-height: 100%;
}
</style>
相关推荐
我是苏苏8 小时前
Web开发:C#通过ProcessStartInfo动态调用执行Python脚本
java·服务器·前端
无羡仙8 小时前
Vue插槽
前端·vue.js
哈__9 小时前
React Native 鸿蒙跨平台开发:PixelRatio 像素适配
javascript·react native·react.js
用户6387994773059 小时前
每组件(Per-Component)与集中式(Centralized)i18n
前端·javascript
SsunmdayKT9 小时前
React + Ts eslint配置
前端
开始学java9 小时前
useEffect 空依赖 + 定时器 = 闭包陷阱?count 永远停在 1 的坑我踩透了
前端
zerosrat9 小时前
从零实现 React Native(2): 跨平台支持
前端·react native
狗哥哥9 小时前
🔥 Vue 3 项目深度优化之旅:从 787KB 到极致性能
前端·vue.js
青莲8439 小时前
RecyclerView 完全指南
android·前端·面试
青莲8439 小时前
Android WebView 混合开发完整指南
android·前端·面试