Reputation: 2223
I'm trying to apply Zoom In/Out like Google Map like here - https://www.google.com/maps/@36.241201,-98.1261798,5.13z?hl=en I cannot get it working properly.
I've looked for solution. But all of them are based on CSS Tansform what i cannot use.
var $image = $('#image');
var container_height = $('#container').height();
var container_width = $('#container').width();
$image.width(container_width);
$('#container').on('click', function(e){
var zoom = 100;
e.preventDefault();
var this_offset = $(this).offset();
var click_x = e.pageX - this_offset.left;
var click_y = e.pageY - this_offset.top;
var image_height = $image.height();
var image_width = $image.width();
$image.css({
'width' : image_width + zoom,
'height' : image_height + zoom,
'top': -click_y,
'left': -click_x,
});
});
.container{
margin: 15px auto;
position:relative;
width:400px;
height: 300px;
border: 2px solid #fff;
overflow:hidden;
box-shadow: 0 0 5px rgba(0,0,0,0.5);
}
.image{
position:absolute;
transition:all 0.25s ease-in-out;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container" id="container">
<img src="https://i.imgur.com/sEUlGOw.jpg" id="image" class="image" />
</div>
Please Help. Thanks
Upvotes: 1
Views: 511
Reputation: 2272
First, please apply the zoom as a multiplication factor. So for a 200%
zoom, set the value to 2
. To zoom out to half size, set the value to 0.5
.
Instead of working with pageX
and pageY
, I've used offsetX and offsetY to find x, y coordinate of pixel which was clicked. (Please be aware of compatibility).
To find image's left and top within container, I've used offsetLeft and offsetTop.
(function () {
var $image = $('#image');
var container_width = $('#container').width();
$image.width(container_width);
$image.on('click', function(e){
var zoom = 1.3; // zoom by multiplying a factor for equal width n height proportions
e.preventDefault();
var click_pixel_x = e.offsetX,
click_pixel_y = e.offsetY;
var image_width = $image.width(),
image_height = $image.height();
var current_img_left = this.offsetLeft,
current_img_top = this.offsetTop;
var new_img_width = image_width * zoom,
//new_img_height = image_height * zoom,
img_left = current_img_left + click_pixel_x - (click_pixel_x * zoom),
img_top = current_img_top + click_pixel_y - (click_pixel_y * zoom);
$image.css({
'width' : new_img_width,
//'height' : new_img_height,
'left': img_left,
'top': img_top
});
});
})(jQuery);
.container{
margin: 15px auto;
position:relative;
width:400px;
height: 300px;
border: 2px solid #fff;
overflow:hidden;
box-shadow: 0 0 5px rgba(0,0,0,0.5);
}
.image{
position:absolute;
left: 0,
top: 0,
transition:all 0.25s ease-in-out;
}
<div class="container" id="container">
<img src="https://i.imgur.com/sEUlGOw.jpg" id="image" class="image" />
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 4