2014-09-23 126 views

回答

2

我已經通過編寫此javascript代碼修復了此問題,它基本上根據圖像大小和容器大小計算縮放和平移參數,並應用轉換以使圖像拉伸到容器邊界。

JavaScript文件

$(document).ready(function(){ 
    $panzoom = $(".cimage").panzoom(); 

    //Wait for the image to load 
    $('.cimage').load(function(){ 
     //Get container and image 
     var image = $('.cimage'); 
     var container = $('.image-container'); 

     //Get container dimensions 
     var container_height = container.height(); 
     var container_width = container.width(); 

     //Get image dimensions 
     var image_height = image.height(); 
     var image_width = image.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 heigh 
     if(image_height > image_width) 
      zoom_factor = container_height/image_height; 
     else 
      zoom_factor = container_width/image_width; 

     //Zoom by zoom_factor 
     $panzoom.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; 
     $panzoom.panzoom("pan", pan_left, pan_top); 

    }); 
}); 

HTML文件

<div class="image-container"> 
    <img class='cimage' src="abc.jpg'/> 
</div> 

它沿着寬度或高度拉伸,根據圖像方向(縱向或橫向),但如果你只想要舒展沿高度則需要更換

if(image_height > image_width) 
    zoom_factor = container_height/image_height; 
else 
    zoom_factor = container_width/image_width; 

zoom_factor = container_height/image_height; 

但我會建議反對,因爲這將不能夠處理圖像的景觀。

+0

這確實提供了混合的結果以及相對較大的圖像以及移動設備。似乎泛計算需要一點調整 – Starboy 2015-05-06 01:09:38

+0

我認爲這將工作,因爲我沒有在平移計算中使用原始圖像寬度和高度,他們在圖像縮小/放大後重新計算。 – 2015-05-07 08:37:50

+0

我發現雖然縮放工作正常,但隨後的平移似乎沒有效果,並且圖像位於視口的右側,而不是中間位置。我看不出如何解決這個問題。 http://stackoverflow.com/questions/32583854/jquery-panzoom-plugin-positioning-image-on-right-with-containinvert?lq=1 – 2015-09-18 12:57:15

相關問題