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>
相关推荐
圣光SG4 分钟前
web操作题练习(五)
前端
杉氧8 分钟前
弹性滚动的奥秘:在 Flutter 中使用 CustomScrollView 与 Sliver 打造极致流畅列表
android·前端·flutter
mONESY15 分钟前
从零搭建 Milvus 向量知识库:Node.js 实现日记 RAG 检索全流程实战
javascript
jinshw16 分钟前
自己实现GIS配图软件(二)
前端·后端·rust
肥胖小羊21 分钟前
企业微信自建应用多环境联调与路由代理方案
服务器·前端·网络
林间码客21 分钟前
全栈视角下的 Mock 指南:从后端单元测试到前端 Vue 3 联调
前端·vue.js·单元测试
张元清22 分钟前
React usePrevious Hook:追踪上一次的 State 和 Props(2026)
javascript·react.js
Cobyte30 分钟前
手写 Rollup 插件实现解析 Vue 文件
前端·javascript·vue.js
IT_陈寒1 小时前
Vue的这个响应式陷阱,我调试了一整天才爬出来
前端·人工智能·后端
莪_幻尘1 小时前
手把手书写你的第一个 AI Skill:从原则到工程化
前端·agent·ai编程