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>
相关推荐
像风一样自由20201 小时前
HTML与JavaScript:构建动态交互式Web页面的基石
前端·javascript·html
aiprtem2 小时前
基于Flutter的web登录设计
前端·flutter
浪裡遊2 小时前
React Hooks全面解析:从基础到高级的实用指南
开发语言·前端·javascript·react.js·node.js·ecmascript·php
why技术2 小时前
Stack Overflow,轰然倒下!
前端·人工智能·后端
幽络源小助理2 小时前
SpringBoot基于Mysql的商业辅助决策系统设计与实现
java·vue.js·spring boot·后端·mysql·spring
GISer_Jing2 小时前
0704-0706上海,又聚上了
前端·新浪微博
止观止3 小时前
深入探索 pnpm:高效磁盘利用与灵活的包管理解决方案
前端·pnpm·前端工程化·包管理器
whale fall3 小时前
npm install安装的node_modules是什么
前端·npm·node.js
烛阴3 小时前
简单入门Python装饰器
前端·python
袁煦丞3 小时前
数据库设计神器DrawDB:cpolar内网穿透实验室第595个成功挑战
前端·程序员·远程工作