Search code examples
javascriptjqueryimagezooming

Javascript / jQuery image zoom plugin


I need to display an image in a fixed size div. Under the div must be some control, like a cursor bar, which sets the resolution of the displayed image. I don't mind much writing the thing, but I thought it might already exist. How come I can't find such a thing ?

(I am not interested in things like jQZoom nor zoomimage which do not let the user choose dynamically the display resolution.)


Solution

  • As this question has now been seen more than 1k times, I add my solution to it. Feel free to copy and adapt.

    The solution involves jQuery UI slider plugin. Mainly we create a div with fixed size, overflow:scroll, containing a img tag, and we add a slider under it. The slider 'change' event is bound to a rescale of the img@width/@height attributes.

    Here is an excerpt of what we did :

    HTML

        <div id="pictureFilePreview">
            <img id="pictureFilePreviewImg" src="style/images/spacer.gif"/>
        </div>
        <div id="pictureSlider"/>
    

    JS

    $('#pictureFilePreview').css('overflow','scroll');
    $('#pictureFilePreviewImg')
        .attr("src", "http://url.of.the.image")
        .css("display","block")
        .bind("load", function(){ //wait for complete load of the image
            // Slider  
            var initHeight = parseInt($('#pictureFilePreviewImg').attr("height"));  
            var initWidth = parseInt($('#pictureFilePreviewImg').attr("width"));  
            if ($('#pictureFilePreview').width() < initWidth 
                || $('#pictureFilePreview').height() < initHeight) {                
    
                var deltaW = $('#pictureFilePreview').width() - initWidth;  
                var deltaH = $('#pictureFilePreview').height() - initHeight;
                var ratio = 0;
                if (deltaW < deltaH) {
                    ratio = ($('#pictureFilePreview').width() / initWidth) * 100;
                } else {
                    ratio = ($('#pictureFilePreview').height() / initHeight) * 100;
                }
                $('#pictureSlider').slider({  
                    range: false,
                    min : ratio,
                    values: [100],
                    change: function(event, ui) {  
                        var newHeight = ((initHeight) * ui.value / 100);  
                        var newWidth = ((initWidth) * ui.value / 100); 
                        $('#pictureFilePreviewImg').attr("height",newHeight);  
                        $('#pictureFilePreviewImg').attr("width",newWidth);  
                        $('#pictureFilePreview').css('overflow',ui.value === 0?'visible':'scroll');  
                    }  
                }); 
            }
        });