Skip to content

Commit

Permalink
feat(zoom): add ability to constrain max zoom to 100% of original ima…
Browse files Browse the repository at this point in the history
…ge size (#7311)

* Add ability to constrain max zoom to 100% of original image size

* check for `gesture.imageEl`

---------

Co-authored-by: Vladimir Kharlampidi <nolimits4web@gmail.com>
  • Loading branch information
broox and nolimits4web authored Feb 27, 2024
1 parent 237e7c4 commit 645f266
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 5 deletions.
20 changes: 15 additions & 5 deletions src/modules/zoom/zoom.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export default function Zoom({ swiper, extendParams, on, emit }) {
extendParams({
zoom: {
enabled: false,
limitToOriginalSize: false,
maxRatio: 3,
minRatio: 1,
toggle: true,
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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;
Expand Down
6 changes: 6 additions & 0 deletions src/types/modules/zoom.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
*
Expand Down

0 comments on commit 645f266

Please sign in to comment.