From 645f266c6b8dea5d43e14cace925ad86236ecc75 Mon Sep 17 00:00:00 2001 From: Derek Brooks Date: Tue, 27 Feb 2024 04:30:36 -0600 Subject: [PATCH] feat(zoom): add ability to constrain max zoom to 100% of original image size (#7311) * Add ability to constrain max zoom to 100% of original image size * check for `gesture.imageEl` --------- Co-authored-by: Vladimir Kharlampidi --- src/modules/zoom/zoom.mjs | 20 +++++++++++++++----- src/types/modules/zoom.d.ts | 6 ++++++ 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/src/modules/zoom/zoom.mjs b/src/modules/zoom/zoom.mjs index 1fff14737..d6b28c793 100644 --- a/src/modules/zoom/zoom.mjs +++ b/src/modules/zoom/zoom.mjs @@ -11,6 +11,7 @@ export default function Zoom({ swiper, extendParams, on, emit }) { extendParams({ zoom: { enabled: false, + limitToOriginalSize: false, maxRatio: 3, minRatio: 1, toggle: true, @@ -87,6 +88,16 @@ export default function Zoom({ swiper, extendParams, on, emit }) { return distance; } + function getMaxRatio() { + const params = swiper.params.zoom; + const maxRatio = gesture.imageWrapEl.getAttribute('data-swiper-zoom') || params.maxRatio; + if (params.limitToOriginalSize && gesture.imageEl && gesture.imageEl.naturalWidth) { + const imageMaxRatio = gesture.imageEl.naturalWidth / gesture.imageEl.offsetWidth; + return Math.min(imageMaxRatio, maxRatio); + } + return maxRatio; + } + function getScaleOrigin() { if (evCache.length < 2) return { x: null, y: null }; const box = gesture.imageEl.getBoundingClientRect(); @@ -158,7 +169,7 @@ export default function Zoom({ swiper, extendParams, on, emit }) { return; } - gesture.maxRatio = gesture.imageWrapEl.getAttribute('data-swiper-zoom') || params.maxRatio; + gesture.maxRatio = getMaxRatio(); } if (gesture.imageEl) { const [originX, originY] = getScaleOrigin(); @@ -476,10 +487,9 @@ export default function Zoom({ swiper, extendParams, on, emit }) { touchY = undefined; } - zoom.scale = - forceZoomRatio || gesture.imageWrapEl.getAttribute('data-swiper-zoom') || params.maxRatio; - currentScale = - forceZoomRatio || gesture.imageWrapEl.getAttribute('data-swiper-zoom') || params.maxRatio; + const maxRatio = getMaxRatio(); + zoom.scale = forceZoomRatio || maxRatio; + currentScale = forceZoomRatio || maxRatio; if (e && !(currentScale === 1 && forceZoomRatio)) { slideWidth = gesture.slideEl.offsetWidth; diff --git a/src/types/modules/zoom.d.ts b/src/types/modules/zoom.d.ts index 0b302c061..658f5baef 100644 --- a/src/types/modules/zoom.d.ts +++ b/src/types/modules/zoom.d.ts @@ -45,6 +45,12 @@ export interface ZoomEvents { } export interface ZoomOptions { + /** + * When set to true, the image will not be scaled past 100% of its original size + * + * @default false + */ + limitToOriginalSize?: boolean; /** * Maximum image zoom multiplier *