Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 2 commits into from
Feb 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading