Skip to content

Instantly share code, notes, and snippets.

@jshbrntt
Last active October 16, 2018 11:10
Show Gist options
  • Select an option

  • Save jshbrntt/f778e4f5a559268a874e to your computer and use it in GitHub Desktop.

Select an option

Save jshbrntt/f778e4f5a559268a874e to your computer and use it in GitHub Desktop.
A simple way of panning and zooming an image using Hammer.js.
// <img id="myimage" src="http://placecage/1280/720">
var image = document.getElementById('myimage');
var mc = new Hammer.Manager(image);
var pinch = new Hammer.Pinch();
var pan = new Hammer.Pan();
pinch.recognizeWith(pan);
mc.add([pinch, pan]);
var adjustScale = 1;
var adjustDeltaX = 0;
var adjustDeltaY = 0;
var currentScale = null;
var currentDeltaX = null;
var currentDeltaY = null;
// Prevent long press saving on mobiles.
webpage.addEventListener('touchstart', function (e) {
e.preventDefault()
});
// Handles pinch and pan events/transforming at the same time;
mc.on("pinch pan", function (ev) {
var transforms = [];
// Adjusting the current pinch/pan event properties using the previous ones set when they finished touching
currentScale = adjustScale * ev.scale;
currentDeltaX = adjustDeltaX + (ev.deltaX / currentScale);
currentDeltaY = adjustDeltaY + (ev.deltaY / currentScale);
// Concatinating and applying parameters.
transforms.push('scale({0})'.format(currentScale));
transforms.push('translate({0}px,{1}px)'.format(currentDeltaX, currentDeltaY));
webpage.style.transform = transforms.join(' ');
});
mc.on("panend pinchend", function (ev) {
// Saving the final transforms for adjustment next time the user interacts.
adjustScale = currentScale;
adjustDeltaX = currentDeltaX;
adjustDeltaY = currentDeltaY;
});
@ivanberry
Copy link
Copy Markdown

Why should recognize pinch and pan? and in my config, the pinch event will always trigger the pan event, This really bother me.

@valentinHruzinski92
Copy link
Copy Markdown

Maybe somebody knows packages where it is implemented?

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