Search code examples
javascriptjquerypinchzoom

Pinch and Zoom Using Javascript/Jquery without plugin


Tried to implement the pinch and zoom without using plugin, but I am able to zoom it but unable to zoom out.

It should support both desktop and tablets. This is what have tried.

JS:

 image = $('#image')
    wrap = $('#wrap')

    width = image.width()
    height = image.height()

    offset = wrap.offset()        

    newX = 0
    newY = 0

    testScale = 1

    image.click (event) ->
        testScale = if event.ctrlKey then (testScale - 0.4) else (testScale + 0.4) 
        pinch event.clientX, event.clientY, testScale

    window.pinch = (x, y, scale) ->

        newWidth = image.width() * scale
        newHeight = image.height() * scale

        # Convert from screen to image coordinates
        x -= offset.left + newX
        y -= offset.top + newY

        newX += -x * (newWidth - width) / newWidth
        newY += -y * (newHeight - height) / newHeight

        image.css '-webkit-transform', "scale3d(#{scale}, #{scale}, 1)"         
        wrap.css '-webkit-transform', "translate3d(#{newX}px, #{newY}px, 0)"

        width = newWidth
        height = newHeight

Demo


Solution

  • I Got This

    var clicks = 0;
    $('#wrap').on("click", function(e){
        clicks++;  //count clicks
            if(clicks === 1) {   
        e.preventDefault();
        $('#wrap img').each(function(index) {
            $(this).animate({
                width: $(this).width() * 1.25,
                height: $(this).height() * 1.25
            });
    
        });
            }
    }).on("dblclick", function(e){
            e.preventDefault();
    
        $('#wrap img').each(function(index) {
            $(this).animate({
                width: $(this).width() / 1.25,
                height: $(this).height() / 1.25
            });
        });
        });
    

    DEMO1

    DEMO2