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>
相关推荐
哈哈哈hhhhhh4 分钟前
vue----v-model
前端·javascript·vue.js
QD_ANJING6 分钟前
2026年大厂前端高频面试原题-React框架200题
开发语言·前端·javascript·react.js·面试·职场和发展·前端框架
happymaker06266 分钟前
web前端学习日记——DAY03(盒子模型,flex布局,表格)
前端·学习
爱丽_12 分钟前
Axios 二次封装:拦截器、统一错误处理与文件下载
前端
24白菜头14 分钟前
若依框架Ruoyi-Vue-SpringBoot3部署
前端·javascript·笔记·后端·学习
光影少年20 分钟前
react的diff算法和vue的diff算法区别
vue.js·算法·react.js
向上的车轮31 分钟前
TypeORM ——TypeScript 生态的主流 ORM对比
javascript·typescript·typeorm
问道飞鱼33 分钟前
【Tauri框架学习】Tauri 与 React 前端集成:通信机制与交互原理详解
前端·学习·react.js·rust·通信
霍理迪38 分钟前
Vue列表过滤与排序
前端·javascript·vue.js
gCode Teacher 格码致知39 分钟前
Javascript提高:Node.js readline 模块 完整使用教程
javascript·node.js