简体   繁体   中英

JavaScript zoom image and center viewable area

I'm trying to create a zoom able image upon click of a button, however the image should be zoomed centered on the view able area, as the image may be bigger than the container.

I've created a fiddle here to illustrate what I want, I'd obviously usually hide the image outside the container, I'm not bothered about that part just now, also put in a border overlay to show the bounds of the container.

I've done the zoom part based on the image ratio, I just need to work out the new top and left css values and apply it to the image after the zoom. Also the image is draggable, so once you move the image it must take into account the position of the image.

Basically, the centrol point of the image within the red container must remain the same after the zoom, so you are effectly zooming in on whatever is at the middle of the container.

http://jsfiddle.net/wFaFg/1/

why do you we need code to link to jsfiddle?

Thanks

edit:

http://jsfiddle.net/FU55w/

getting close with the above fiddle, but still not zooming completely on central point

So I found the solution,

It is slightly more complex than just finding out how much the image increased in size.

I work out the x & y value of the center point of the image within the container, by taking the left and top value, turning it positive then adding half the container width and height.

var x = Math.abs(image.position().left) + container.width() / 2
var y = Math.abs(image.position().top) + container.height() / 2

I work out the ratio of the image scale by dividing the new width by the old width, then I can multiply the x & y value by the ratio.

Then take the difference between the new x and y away from the current left and top.

image.position().left - (newX - x)
image.position().top - (newY - y)

Complete fiddle: http://jsfiddle.net/fbd2mk5q/

Try the new fiddle based on your comment:

http://jsfiddle.net/wFaFg/6/

$("#zoom").on("click", function(e)
{
    var container = $("#container");
    var image = $("#container img");
    var curLeft = image.position().left;
    var curTop = image.position().top;
    var ratio = image.height() / image.width();

    image.css({
        height: image.height() + (20 * ratio),
        width: image.width() + (20 * ratio),
        left: curLeft - ((20 * ratio)/2),
        top: curTop - ((20 * ratio)/2)
    });
});

http://www.hklabs.org/articles/image_zooming_with_javascript

Here is the excellent tutorial that i have made on the same topic ! Use a seperate division with background as some part of your image. other part of the image can be hidden with background-repeat:no-repeat; now use the background-position property to move your image inside the division !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM