diff --git a/src/image-preview/ImagePreview.js b/src/image-preview/ImagePreview.js index a09f58c3f..2cfda607d 100644 --- a/src/image-preview/ImagePreview.js +++ b/src/image-preview/ImagePreview.js @@ -84,6 +84,10 @@ export default createComponent({ }, data() { + this.imageSizes = []; + this.windowWidth = window.innerWidth; + this.windowHeight = window.innerHeight; + return { scale: 1, moveX: 0, @@ -180,16 +184,24 @@ export default createComponent({ startMove(event) { const image = event.currentTarget; - const rect = image.getBoundingClientRect(); - const winWidth = window.innerWidth; - const winHeight = window.innerHeight; - this.touchStart(event); + this.setMaxMove(image.dataset.index); this.moving = true; this.startMoveX = this.moveX; this.startMoveY = this.moveY; - this.maxMoveX = Math.max(0, (rect.width - winWidth) / 2); - this.maxMoveY = Math.max(0, (rect.height - winHeight) / 2); + }, + + setMaxMove(index) { + const { scale, windowWidth, windowHeight } = this; + + if (this.imageSizes[index]) { + const { displayWidth, displayHeight } = this.imageSizes[index]; + this.maxMoveX = Math.max(0, (displayWidth * scale - windowWidth) / 2); + this.maxMoveY = Math.max(0, (displayHeight * scale - windowHeight) / 2); + } else { + this.maxMoveX = 0; + this.maxMoveY = 0; + } }, startZoom(event) { @@ -199,6 +211,31 @@ export default createComponent({ this.startDistance = getDistance(event.touches); }, + onImageLoad(event, index) { + const { windowWidth, windowHeight } = this; + const { naturalWidth, naturalHeight } = event.target; + const windowRatio = windowHeight / windowWidth; + const imageRatio = naturalHeight / naturalWidth; + + let displayWidth; + let displayHeight; + + if (imageRatio < windowRatio) { + displayWidth = windowWidth; + displayHeight = windowWidth * imageRatio; + } else { + displayWidth = windowHeight / imageRatio; + displayHeight = windowHeight; + } + + this.imageSizes[index] = { + naturalWidth, + naturalHeight, + displayWidth, + displayHeight, + }; + }, + onImageTouchStart(event) { const { touches } = event; const { offsetX = 0 } = this.$refs.swipe || {}; @@ -335,12 +372,16 @@ export default createComponent({ src={image} fit="contain" class={bem('image')} + data-index={index} scopedSlots={imageSlots} style={index === this.active ? this.imageStyle : null} nativeOnTouchstart={this.onImageTouchStart} nativeOnTouchmove={this.onImageTouchMove} nativeOnTouchend={this.onImageTouchEnd} nativeOnTouchcancel={this.onImageTouchEnd} + onLoad={(event) => { + this.onImageLoad(event, index); + }} /> ))} diff --git a/src/image-preview/test/__snapshots__/index.spec.js.snap b/src/image-preview/test/__snapshots__/index.spec.js.snap index 828a38b64..06a8e087f 100644 --- a/src/image-preview/test/__snapshots__/index.spec.js.snap +++ b/src/image-preview/test/__snapshots__/index.spec.js.snap @@ -61,7 +61,7 @@ exports[`set show-index prop to false 1`] = ` `; exports[`zoom 1`] = ` -
+