Skip to content

Instantly share code, notes, and snippets.

@leye0
Created January 7, 2017 06:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leye0/f4a503c9142346aa256196c3360d1f81 to your computer and use it in GitHub Desktop.
Save leye0/f4a503c9142346aa256196c3360d1f81 to your computer and use it in GitHub Desktop.
Make an element zoomable and draggable
$('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
}
});
});
@leye0
Copy link
Author

leye0 commented Jan 7, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment