我正在尝试使用jQuery Panzoom插件,它大部分都很好,除了......
我希望最初缩放大图像以适合容器,并已contain: 'invert'
启用。我已经对这个示例进行了调整,以便在首次加载图像时对其进行缩放和定位。
这很好用,图像位于(窗口大小)容器的中心。但如果我contain: 'invert'
用作 Panzoom 选项,图像位于右侧。我不知道为什么。
你可以在这里看到它的实际效果:https ://jsfiddle.net/7ugm9z51/2/
这是 HTML/CSS:
.zoom-container {
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
}
<div class="zoom-container">
<img class="zoom-img" src="https://farm8.staticflickr.com/7314/15854478283_d2667a7264_o.jpg">
</div>
和 JavaScript:
$('.zoom-img').panzoom({
// Causes image to appear aligned right:
contain: 'invert',
});
// Get container dimensions
var container_height = $('.zoom-container').height();
var container_width = $('.zoom-container').width();
// Get image dimensions
var image_height = $('.zoom-img').height();
var image_width = $('.zoom-img').width();
// Calculate the center of image since origin is at x:50% y:50%
var image_center_left = image_width / 2.0;
var image_center_top = image_height / 2.0;
// Calculate scaling factor
var zoom_factor;
// Check to determine whether to stretch along width or height
if(image_height > image_width) {
zoom_factor = container_height / image_height;
} else {
zoom_factor = container_width / image_width;
};
// Zoom by zoom_factor
$('.zoom-img').panzoom('option', 'minScale', zoom_factor);
$('.zoom-img').panzoom('zoom', zoom_factor, {animate: false});
// Calculate new image dimensions after zoom
image_width = image_width * zoom_factor;
image_height = image_height * zoom_factor;
// Calculate offset of the image after zoom
var image_offset_left = image_center_left - (image_width / 2.0);
var image_offset_top = image_center_top - (image_height / 2.0);
// Calculate desired offset for image
var new_offset_left = (container_width - image_width) / 2.0;
var new_offset_top = (container_height - image_height) / 2.0;
// Pan to set desired offset for image
var pan_left = new_offset_left - image_offset_left;
var pan_top = new_offset_top - image_offset_top;
$('.zoom-img').panzoom('pan', pan_left, pan_top);