Search code examples
javascriptiscroll

iScroll zoom factor calculation


I have a problem and really hope someone could help me out.

JSFiddle: https://jsfiddle.net/EstSiim/zjqptg9j/3/

HTML:

<div id="wrapper">

    <div id="content">

    </div>

</div>

<br><br><br>

<button id="btn">Zoom to view</button>

CSS:

#wrapper {
    width: 500px;
    height: 500px;
    border: 1px solid black; 
    overflow: hidden;
    position: relative;
}

#content {
    width: 700px;
    height: 300px;
    background-color: blue;
}

JavaScript:

var myScroll = new IScroll('#wrapper', {
        mouseWheel: true,
        keyBindings: true,
        wheelAction: 'zoom',
        scrollbars: true,
        scrollX: true,
        scrollY: true,
        zoomMin: 0.1,
        zoom: true, 
        mouseWheelSpeed: 20,
});


var zoomFactor = 0.4;  //need to calculate this somehow

$('#btn').on('click', function() {

    myScroll.zoom(myScroll.scale - zoomFactor);

});

So basically what i want is iScroll (https://github.com/cubiq/iscroll) to zoom out so all of its content is showing. Problem is that its content size is not fixed (it can be 700x300, 2000x3000, 200x900 and so on).

Thank you for your time


Solution

  • Use this method, if i understand correct you want to reset the content, I implemented this on both dimensions (width vs height), if you need only one of it modify fit factor to return the exact percent of dimension (no max just pick one to return), fiddle here:

    //get wrapper dimensions
    var wrap = {
        H : $('#wrapper').height(),
        W : $('#wrapper').width()
    }
    //get content dimensions
    var content = {
        H : $('#content').height(),
        W : $('#content').width(),
       };
    
    var myScroll = new IScroll('#wrapper', {
            mouseWheel: true,
            keyBindings: true,
            wheelAction: 'zoom',
            scrollbars: true,
            scrollX: true,
            scrollY: true,
            zoomMin: 0.1,
            zoom: true, 
            mouseWheelSpeed: 20,
    });
    //compute reset zoom factor
    var fitFactor = function ()
    {
        //compute witch dimension is larger width vs height
        h = content.H / wrap.H;//zoom factor for height
        w = content.W/ wrap.W;//zoom factor for width
        //get max between zoom factores, remove percents
        renderedFactor = Math.max(h, w);
        //return scale factor
        return  1/renderedFactor;
    };
    
    $('#btn').on('click', function() {
        myScroll.zoom(fitFactor());
     });