Jcrop Handle Destroy

时间:2014-05-06 13:21:31

标签: jquery jcrop

我允许多张图片上传,因此我需要销毁jcrop上的句柄,以便在图片窗格中显示新图片。我使用以下代码。

我只需要一种方法让句柄从当前的图像绑定中释放出来,并通过这段代码释放出来运行另一个图像。

    $scope.cropImage = function(file) {

    $scope.currentFile = file;
    $("#target").attr("src", file.url);
    $("#imageModal").modal("show");


    var jcrop_api,
        boundx,
        boundy,

        // Grab some information about the preview pane
        $preview = $('#preview-pane'),
        $pcnt = $('#preview-pane .preview-container'),
        $pimg = $('#preview-pane .preview-container img'),

        xsize = $pcnt.width(),
        ysize = $pcnt.height();

    $timeout(function () {
        if(jcropHandle != null) {
            jcropHandle.destroy();
        }
        jcropHandle = $('#target').Jcrop({
          onChange: updatePreview,
          onSelect: updatePreview,
          aspectRatio: xsize / ysize
        },function(){
          // Use the API to get the real image size
          var bounds = this.getBounds();
          boundx = bounds[0];
          boundy = bounds[1];
          // Store the API in the jcrop_api variable
          jcrop_api = this;

          // Move the preview into the jcrop container for css positioning
          $preview.appendTo(jcrop_api.ui.holder);
        });
    }, 0);

    function updatePreview(c)
    {
      $scope.coordinates.x1 = c.x;
      $scope.coordinates.x2 = c.x2;
      $scope.coordinates.y1 = c.y;
      $scope.coordinates.y2 = c.y2;
      if (parseInt(c.w) > 0)
      {
        var rx = xsize / c.w;
        var ry = ysize / c.h;

        $pimg.css({
          width: Math.round(rx * boundx) + 'px',
          height: Math.round(ry * boundy) + 'px',
          marginLeft: '-' + Math.round(rx * c.x) + 'px',
          marginTop: '-' + Math.round(ry * c.y) + 'px'
        });
      }
    };
};

$('.image-resize').each(function(i, item) {
    var img_height = $(item).height();
    var div_height = $(item).parent().height();
    if(img_height<div_height){
        //IMAGE IS SHORTER THAN CONTAINER HEIGHT - CENTER IT VERTICALLY
        var newMargin = (div_height-img_height)/2+'px';
        $(item).css({'margin-top': newMargin });
    }else if(img_height>div_height){
        //IMAGE IS GREATER THAN CONTAINER HEIGHT - REDUCE HEIGHT TO CONTAINER MAX - SET WIDTH TO AUTO  
        $(item).css({'width': 'auto', 'height': '100%'});
        //CENTER IT HORIZONTALLY
        var img_width = $(item).width();
        var div_width = $(item).parent().width();
        var newMargin = (div_width-img_width)/2+'px';
        $(item).css({'margin-left': newMargin});
    }
});

2 个答案:

答案 0 :(得分:6)

这是我从元素中删除Jcrop的方法,因此我可以将它与其他图像一起使用。

if ($('#target').data('Jcrop')) {
   $('#target').data('Jcrop').destroy();
}

答案 1 :(得分:1)

如果你需要重新使用JCrop,在破坏时从img移除样式attr,因为样式将保留,如果新图像具有不同的分辨率,它将产生错误的裁剪。 添加到astrocrack解决方案(抱歉,我无法评论您的回复)

if ($('#target').data('Jcrop')) {
    $('#target').data('Jcrop').destroy();
    $('#target').removeAttr('style');
}