Reputation: 69
I've been assigned to make an image zoom in and zoom out javascript application, but with draggable image and when zoom in and out I must keep the viewing center of the container , in the center. I've done the zoom in part with all the calculation and keeping left, top ratio. using this http://jsfiddle.net/phHqQ/
$("#zoom").on("click", function (e) {
var container = $("#container");
var image = $("#container img");
var css = {};
css.height = image.height() + (image.height() * 0.2);
css.width = image.width() + (image.width() * 0.2);
var x = Math.abs(image.position().left) + container.width() / 2;
var y = Math.abs(image.position().top) + container.height() / 2;
var ratio = css.width / image.width();
var newX = x * ratio;
var newY = y * ratio;
css.left = image.position().left - (newX - x);
css.top = image.position().top - (newY - y);
image.css(css);
});
please anyone can guide/make the zoom out feature from it
Upvotes: 1
Views: 1578
Reputation: 14541
You could begin with your zoom-in function, and start by reducing the image's height-width. So, instead of adding to the height and width, you will now subtract from them.
css.height = image.height() - (image.height() * 0.2);
css.width = image.width() - (image.width() * 0.2);
Once you do this, the zoom-out functionality will start to work, but soon you'll realize that once you get to a size less than original, the image will start to develop a left-top margin. To prevent this, you need to check if the left
and top
values are getting positive during zoom out. If they do, you can set them to 0
so that the image will be moved to the top-left corner anyway.
css.left = css.left > 0 ? 0 : css.left;
css.top = css.top > 0 ? 0 : css.top;
As you go on, you will notice a few more of such problems, and you will have to handle some more scenarios to prevent the margins from growing.
Here's a fiddle: http://jsfiddle.net/phHqQ/261/
At the time of zooming in, based on the center of container, some part of image might go out of the container, and it may develop some margin in the bottom-right part of the container. You could add these validations in the zoom-in function to ensure that whenever possible, while zooming in, the image will stay within the container.
if(css.height + css.top < 200){
css.top = 200 - css.height;
}
if(css.width + css.left < 300) {
css.left = 300 - css.width;
}
Here's the fiddle updated with this code: http://jsfiddle.net/phHqQ/262/
Upvotes: 1