vue中实现图片拖动、放大、缩小,拖动不影响编辑

3,278 阅读1分钟

封装成组件,可以直接在需要的页面调用,只接收两个值show和ur1,使用自定义指令实现拖动

<template>
  <div class="drag">
    <div v-show="show" v-drag class="content" style="width:500px;z-index: 20">
      <img
        id="target"
        ref="element"
        class="target"
        style="width: 100%;"
        :style="{ transform: 'scale(' + multiples + ')' + 'rotate(' + current + 'deg)' }"
        :src="src"
      >
    </div>
    <div v-show="show" class="button">
      <el-button size="mini" type="success" @click="handleClose">关闭</el-button>
      <el-button size="mini" type="success" @click="handlerotate">旋转</el-button>
      <el-button size="mini" type="success" @click="handlebig">放大</el-button>
      <el-button size="mini" type="success" @click="handleReduce">缩小</el-button>
    </div>
  </div>
</template>
<script>
export default {
  directives: {
    drag(el) {
      const oDiv = el
      oDiv.onmousedown = function(e) {
        const disX = e.clientX - oDiv.offsetLeft
        const disY = e.clientY - oDiv.offsetTop
        document.onmousemove = function(e) {
          const l = e.clientX - disX
          const t = e.clientY - disY
          oDiv.style.left = l + 'px'
          oDiv.style.top = t + 'px'
        }
        document.onmouseup = function() {
          document.onmousemove = null
          document.onmouseup = null
        }
        return false
      }
    }
  },
  props: {
    shows: {
      type: Boolean,
      default: null
    },
    url: {
      type: String || Number,
      default: null
    }
  },
  data() {
    return {
      dd: '',
      inout: '',
      show: '',
      current: 0,
      name: '',
      src: '',
      multiples: 1
    }
  },
  watch: {
    shows() {
      this.show = this.shows
      if (this.shows) {
        this.src = this.url
        this.$nextTick(() => {
          if (this.$refs.element.offsetHeight > 600) {
            this.multiples = '0.2'
          }
        })
      }
    }
  },
  methods: {
    handlerotate() {
      this.current = (this.current + 90) % 360
    },
    handlebig() {
      this.multiples = Number(this.multiples) + 0.1
    },
    handleReduce() {
      this.multiples = Number(this.multiples) - 0.1
    },
    handleClose() {
      this.$emit('update:shows', false)
    }
  }
}
</script>
<style>
.drag {
  position: relative;
  height: 100%;
}
.content {
  position: fixed;
  transform: translate(-50%, -50%);
  left: 50%;
  /* top: 50%; */
  cursor: pointer;
}
.target {
 text-align: center;
 display: inline-block;
  -webkit-box-shadow: #666 0px 0px 10px;
   -moz-box-shadow: #666 0px 0px 10px;
   box-shadow: #666 0px 0px 10px;
   background: #EEFF99;
}
.button {
  position: fixed;
  transform: translate(-50%, -50%);
  left: 50%;
  top: 95%;
  z-index: 200;
}
</style>

1.png