Last active
October 16, 2018 11:10
-
-
Save jshbrntt/f778e4f5a559268a874e to your computer and use it in GitHub Desktop.
A simple way of panning and zooming an image using Hammer.js.
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
// <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; | |
}); |
Sorry, the meta tag has been still deleted....??
I solved and also posted an answer on Stackoverflow to an user who experienced my same problem. I discovered that console said that the mc.get() returned a null value. As a matter of fact, with my above statements, the mc object.recognizers array was void.
So I used this way to initializate the hammer instance:
var mc = new Hammer.Manager(myElement, { recognizers: [ [Hammer.Pinch, {enable: false}] ] });
and now it works.
Why should recognize pinch and pan? and in my config, the pinch event will always trigger the pan event, This really bother me.
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
...the first part of my code has been cutted in my previous message...I wanted to add it here but it is not shown....I don't know why...
Anyway there was the meta tag that suppress the native pinch to zoom function.. i.e.
and the html doctype declaration, the html and head tags openings