功能一览
- 图片缩放
- 图片旋转
- 图片拖拽
组件使用 vue 编写,可直接使用:
<ImagePreview:src="previewSrc":show.sync="previewShow"/>
<template><divclass="image-preview"v-if="show"@mousewheel.prevent="scaleImg"@mouseup="onMouseUp"@mousemove="move"><div class="image-preview__mask" @click="hide" /><imgclass="image-preview__img":src="src":style="imgStyle"@dragstart.prevent@mousedown="onMouseDown"><div class="image-preview__option"><a @click.stop="rotate(1)" @mouseup.stop><img src="https://img1.dxycdn.com/2018/1122/584/3313301195686592508-2.png"></a><a @click.stop="rotate(2)" @mouseup.stop><img src="https://img1.dxycdn.com/2018/1122/118/3313301195686709591-2.png"></a></div></div></template><script>export default {name: 'ImagePreview',props: {show: {type: Boolean,default: false},src: {type: String,default: ''}},data () {return {scale: 0,startX: 0,startY: 0,moveX: 0,moveY: 0,x: 0,y: 0,angle: 0,onMove: false}},computed: {imgStyle () {return {transform: `scale(${1 + this.scale * 0.1}) rotate(${this.angle}deg)`,top: `${this.moveY || this.y}px`,left: `${this.moveX || this.x}px`,cursor: this.onMove ? 'grabbing' : 'grab'}}},watch: {'show' (newVal) {if (!newVal) {this.scale = 0this.startX = 0this.startY = 0this.x = 0this.y = 0this.onMove = false}}},methods: {hide () {this.$emit('update:show', false)},scaleImg (e) {if (e.deltaY < 0) {this.scale += 1} else if (this.scale > -9) {this.scale -= 1}},onMouseDown (e) {if (e.button !== 0) returnthis.onMove = truethis.startX = e.clientXthis.startY = e.clientYreturn false},onMouseUp () {this.onMove = falseif (this.moveX === 0 && this.moveY === 0) returnthis.x = this.moveXthis.y = this.moveYthis.moveX = 0this.moveY = 0},move (e) {if (this.onMove) {this.moveX = this.x + e.clientX - this.startXthis.moveY = this.y + e.clientY - this.startY}},rotate (direct) {if (direct === 1) {this.angle -= 90} else {this.angle += 90}}}}</script><style lang="less" scoped>.image-preview {position: fixed;top: 0;right: 0;bottom: 0;left: 0;z-index: 3000;text-align: center;&__mask {position: absolute;width: 100%;height: 100%;background: rgba(0, 0, 0, 0.75);cursor: url('~@/assets/images/close2.png'),auto;}&__img {position: relative;max-width: 100%;max-height: 100%;transition: transform 0.2s;}&__option {background: rgba(0, 0, 0, 0.349);position: fixed;height: 70px;padding:5px 0;bottom:0;left:0;width: 100%;text-align: center;a {display:inline-block;line-height: 0;border-radius: 3px;&:hover{background: rgba(255, 255, 255, 0.3);}img {max-width: 70px;max-height: 70px;will-change: transform;}}}}</style>
代码来自 dxyer
