Question

I'm trying to create a image cropper that should work on mobile; A big image is contained inside a container element that crops it, the user can drag the image inside this container and pinch to zoom.

The drag functionality works on desktop browser but when I'm testing in on mobile browser (android chrome, android internet browser, iphone safari), it doesn't work properly: it's not smooth or doesn't drag at all. It moves just a tiny, very tiny bits when trying to swipe or touch move.

Did some tests with touch, touchstart, touchmove without much luck:

I've got a demo in the following link ( http://jsbin.com/cokil/1/ ). Not sure if I can get some tips or advice on how to do this ?

  • it was reported that the raw github link didn't load hammerjs (is loading here), so I've got this other loading it from a CDN http://jsbin.com/cokil/3/

  • please remember that the issue is with mobile browsers

Thanks for looking!

Was it helpful?

Solution

Your jsbin is not including Hammer js correctly. Replace:

https://raw.github.com/EightMedia/hammer.js/master/hammer.min.js

with

//cdnjs.cloudflare.com/ajax/libs/hammer.js/1.0.6/hammer.min.js

and your script works fine.


there is no need for jQuery in the script as it stands. You can use the native DOMContentLoaded and remove $(document).ready if you like.


You also need to add 'px' to the end of your top and left declarations

imgEl.style.top = (y + parseFloat(event.gesture.deltaY))+'px';
imgEl.style.left = (x + parseFloat(event.gesture.deltaX))+'px';

DEMO

OTHER TIPS

After researching quiet a lot, listening to what other people had to say about this and trying to keep things simple, I've come up with the following solution and hope is useful for someone else in the future:

        document.addEventListener('touchstart', function(event) {
             event.preventDefault();
             var e = new Event('dragstart'); 
             element.dispatchEvent(e);
        }, false);

        document.addEventListener('touchmove', function(event) {
            event.preventDefault();
            var e = new Event('drag'); 
            element.dispatchEvent(e);
        }, false);

This works by triggering the original code, that works on desktop:

        Hammer(element).on("dragstart", function(event) {

            imgEl = document.querySelectorAll("img")[0];

            y = parseFloat(imgEl.style.top) || 0;
            x = parseFloat(imgEl.style.top) || 0;
        });

        Hammer(element).on("drag", function(event) {

            imgEl.style.top = y + parseFloat(event.gesture.deltaY);
            imgEl.style.left = x + parseFloat(event.gesture.deltaX);

        });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top