2013-03-11 49 views
1

我正在使用jQuery和imgAreaSelect插件。我正在使用區域選擇插件,以便用戶在上傳之前可以將其圖像裁剪爲16:9寬高比。jQuery imgAreaSelect設置初始選擇與長寬比

我想顯示一個初始的作物選擇,這樣當他們選擇文件時,會加載一個縮略圖,並使用imgAreaSelect選擇最大可能的16:9選擇。我有縮略圖加載等,但不能得到寬高比的一部分。這是我到目前爲止:

// adds an image area select instance 
    function addImgAreaSelect(img){ 
      img.addClass('imgAreaSelect').imgAreaSelect({ 
        handles : true, 
        aspectRatio : '16:9', 
        fadeSpeed : 1, 
        show : true 
      }); 
      img.load(function(){ // set initial crop at 16:9 aspect ratio, calculate coordinates 
        // @todo 
        $(this).imgAreaSelect({ x1 : 0, y1 : 0, x2 : this.width, y2 : this.height }); 

    }); 
} 

任何幫助,這是表示讚賞!由於

+0

要調用imgAraSelect 2次就調用初始作物選擇?我不明白 – Notflip 2014-08-27 11:41:25

+0

@MiguelStevens看到下面的解決方案。第二次調用imgAreaSelect以新值更新它(在這種情況下是作物選擇)。它不重新初始化整個插件,只更新值。 – conor 2014-08-27 16:05:36

回答

9

這個工作對我來說:

// adds an image area select instance 
function addImgAreaSelect(img){ 
     img.addClass('imgAreaSelect').imgAreaSelect({ 
       handles : true, 
       aspectRatio : '16:9', 
       fadeSpeed : 1, 
       show : true 
     }); 
     img.load(function(){ // display initial image selection 16:9 
        var height = (this.width/16) * 9; 
        if(height <= this.height){  
          var diff = (this.height - height)/2; 
          var coords = { x1 : 0, y1 : diff, x2 : this.width, y2 : height + diff }; 
        } 
        else{ // if new height out of bounds, scale width instead 
          var width = (this.height/9) * 16; 
          var diff = (this.width - width)/2; 
          var coords = { x1 : diff, y1 : 0, x2 : width + diff, y2: this.height }; 
        } 
       $(this).imgAreaSelect(coords); 
     }); 
} 
1

通過添加以下代碼

$('#thumbnail').imgAreaSelect({ x1 : 0, y1 : 0, x2 : 180, y2: 180, aspectRatio: '1:1', handles: true , onSelectChange: preview }); 
0

function addImgAreaSelect(img){ 
 
     img.addClass('imgAreaSelect').imgAreaSelect({ 
 
       handles : true, 
 
       aspectRatio : '16:9', 
 
       fadeSpeed : 1, 
 
       show : true 
 
     }); 
 
     img.load(function(){ 
 
       var ratio = 19/9; 
 
       var originalH = originalImg.height; 
 
       var originalW = originalImg.width; 
 
       var size = Math.min(thumb.width()/ratio, thumb.height()); 
 
       var xBiggerThanY = thumb.width()/ratio > thumb.height(); 
 
       var fullSize = Math.max(thumb.width()/ratio, thumb.height()); 
 
       var sizeX1 = xBiggerThanY ? (fullSize - size) * ratio/2 : 0; 
 
       var sizeX2 = xBiggerThanY ? size*ratio-1 + (fullSize - size) * ratio/2 : size*ratio-1; 
 
       var sizeY1 = xBiggerThanY ? 0 : (fullSize - size)/2; 
 
       var sizeY2 = xBiggerThanY ? size - 1 : size - 1 + (fullSize - size)/2; 
 

 
       var initSelection = {x1: sizeX1, y1: sizeY1, x2: sizeX2, y2: sizeY2}; 
 
       $(this).imgAreaSelect(initSelection); 
 
     }); 
 
}