Created
January 7, 2017 06:52
-
-
Save leye0/f4a503c9142346aa256196c3360d1f81 to your computer and use it in GitHub Desktop.
Make an element zoomable and draggable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$('document').ready(() => { | |
let zoom = 1; | |
let nContainer = document.getElementById('container'); // Get zoomed element | |
let originalOffset; // We'll retain original zoomed element offset | |
$(nContainer).draggable(); // Use jQuery UI plugin to make zoomed element draggable | |
$('.zoomable').on('mousewheel', function (e) { | |
e.preventDefault(); | |
let zoomOut = e.originalEvent.deltaY > 0; | |
if ((zoomOut && zoom === 1) || (!zoomOut && zoom === 100)) return; // Ignore action | |
if (!originalOffset) originalOffset = {left: nContainer.offsetLeft, top: nContainer.offsetTop }; // Memorizes original zoomed element offsets | |
zoom *= zoomOut ? 0.92 : 1.08; // Increases or decreases zoom | |
zoom = zoom < 1 ? 1 : zoom > 100 ? 100 : zoom; // Limit zoom range to [1-25] | |
nContainer.style.transform = 'scale(' + zoom + ', ' + zoom + ') translateZ(0)'; // Zooms! | |
if (!zoomOut && e.currentTarget === nContainer) { // Only set focal if zooming inside image | |
let rx = e.offsetX / nContainer.clientWidth; // Determines horizontal focal | |
let ry = e.offsetY / nContainer.clientHeight; // Determines vertical focal | |
let cursorX = e.clientX - originalOffset.left; // Original cursor position | |
let diffX = cursorX - e.offsetX; // Offset-fix to apply to focal to zoom exactly over the cursor | |
let cursorY = e.clientY - originalOffset.top; // '' | |
let diffY = cursorY - e.offsetY; // '' | |
if (diffX !== 0) nContainer.style.left = (diffX) + 'px'; // Fix position to zoom over cursor | |
if (diffY !== 0) nContainer.style.top = (diffY) + 'px'; | |
nContainer.style.transformOrigin = (rx * 100) + '% '+ (ry * 100) + '%'; // Set focal | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://jsfiddle.net/wgdxw0dt/30/