2016-03-05 7 views
0

Привет, я хотел бы использовать fengyuanchen/cropper JS (Crop Avatar) в моей системе. Но я не могу изменить соотношение сторон для каждой страницы. Поскольку соотношение сторон находится в файле main.js с jquery.Как изменить соотношение сторон в fengyuanchen/cropper JS (Crop Avatar)

Так я хотел бы determinite apect соотношение в index.html

Вот Коды

main.js (PS: Соотношение сторон находится на линии 201.)

(function (factory) { 
 
    if (typeof define === 'function' && define.amd) { 
 
    // AMD. Register as anonymous module. 
 
    define(['jquery'], factory); 
 
    } else if (typeof exports === 'object') { 
 
    // Node/CommonJS 
 
    factory(require('jquery')); 
 
    } else { 
 
    // Browser globals. 
 
    factory(jQuery); 
 
    } 
 
})(function ($) { 
 

 
    'use strict'; 
 

 
    var console = window.console || { log: function() {} }; 
 

 
    function CropAvatar($element) { 
 
    this.$container = $element; 
 

 
    this.$avatarView = this.$container.find('.avatar-view'); 
 
    this.$avatar = this.$avatarView.find('img'); 
 
    this.$avatarModal = this.$container.find('#avatar-modal'); 
 
    this.$loading = this.$container.find('.loading'); 
 

 
    this.$avatarForm = this.$avatarModal.find('.avatar-form'); 
 
    this.$avatarUpload = this.$avatarForm.find('.avatar-upload'); 
 
    this.$avatarSrc = this.$avatarForm.find('.avatar-src'); 
 
    this.$avatarData = this.$avatarForm.find('.avatar-data'); 
 
    this.$avatarInput = this.$avatarForm.find('.avatar-input'); 
 
    this.$avatarSave = this.$avatarForm.find('.avatar-save'); 
 
    this.$avatarBtns = this.$avatarForm.find('.avatar-btns'); 
 

 
    this.$avatarWrapper = this.$avatarModal.find('.avatar-wrapper'); 
 
    this.$avatarPreview = this.$avatarModal.find('.avatar-preview'); 
 

 
    this.init(); 
 
    } 
 

 
    CropAvatar.prototype = { 
 
    constructor: CropAvatar, 
 

 
    support: { 
 
     fileList: !!$('<input type="file">').prop('files'), 
 
     blobURLs: !!window.URL && URL.createObjectURL, 
 
     formData: !!window.FormData 
 
    }, 
 

 
    init: function() { 
 
     this.support.datauri = this.support.fileList && this.support.blobURLs; 
 

 
     if (!this.support.formData) { 
 
     this.initIframe(); 
 
     } 
 

 
     this.initTooltip(); 
 
     this.initModal(); 
 
     this.addListener(); 
 
    }, 
 

 
    addListener: function() { 
 
     this.$avatarView.on('click', $.proxy(this.click, this)); 
 
     this.$avatarInput.on('change', $.proxy(this.change, this)); 
 
     this.$avatarForm.on('submit', $.proxy(this.submit, this)); 
 
     this.$avatarBtns.on('click', $.proxy(this.rotate, this)); 
 
    }, 
 

 
    initTooltip: function() { 
 
     this.$avatarView.tooltip({ 
 
     placement: 'bottom' 
 
     }); 
 
    }, 
 

 
    initModal: function() { 
 
     this.$avatarModal.modal({ 
 
     show: false 
 
     }); 
 
    }, 
 

 
    initPreview: function() { 
 
     var url = this.$avatar.attr('src'); 
 

 
     this.$avatarPreview.html('<img src="' + url + '">'); 
 
    }, 
 

 
    initIframe: function() { 
 
     var target = 'upload-iframe-' + (new Date()).getTime(); 
 
     var $iframe = $('<iframe>').attr({ 
 
      name: target, 
 
      src: '' 
 
      }); 
 
     var _this = this; 
 

 
     // Ready ifrmae 
 
     $iframe.one('load', function() { 
 

 
     // respond response 
 
     $iframe.on('load', function() { 
 
      var data; 
 

 
      try { 
 
      data = $(this).contents().find('body').text(); 
 
      } catch (e) { 
 
      console.log(e.message); 
 
      } 
 

 
      if (data) { 
 
      try { 
 
       data = $.parseJSON(data); 
 
      } catch (e) { 
 
       console.log(e.message); 
 
      } 
 

 
      _this.submitDone(data); 
 
      } else { 
 
      _this.submitFail('Image upload failed!'); 
 
      } 
 

 
      _this.submitEnd(); 
 

 
     }); 
 
     }); 
 

 
     this.$iframe = $iframe; 
 
     this.$avatarForm.attr('target', target).after($iframe.hide()); 
 
    }, 
 

 
    click: function() { 
 
     this.$avatarModal.modal('show'); 
 
     this.initPreview(); 
 
    }, 
 

 
    change: function() { 
 
     var files; 
 
     var file; 
 

 
     if (this.support.datauri) { 
 
     files = this.$avatarInput.prop('files'); 
 

 
     if (files.length > 0) { 
 
      file = files[0]; 
 

 
      if (this.isImageFile(file)) { 
 
      if (this.url) { 
 
       URL.revokeObjectURL(this.url); // Revoke the old one 
 
      } 
 

 
      this.url = URL.createObjectURL(file); 
 
      this.startCropper(); 
 
      } 
 
     } 
 
     } else { 
 
     file = this.$avatarInput.val(); 
 

 
     if (this.isImageFile(file)) { 
 
      this.syncUpload(); 
 
     } 
 
     } 
 
    }, 
 

 
    submit: function() { 
 
     if (!this.$avatarSrc.val() && !this.$avatarInput.val()) { 
 
     return false; 
 
     } 
 

 
     if (this.support.formData) { 
 
     this.ajaxUpload(); 
 
     return false; 
 
     } 
 
    }, 
 

 
    rotate: function (e) { 
 
     var data; 
 

 
     if (this.active) { 
 
     data = $(e.target).data(); 
 

 
     if (data.method) { 
 
      this.$img.cropper(data.method, data.option); 
 
     } 
 
     } 
 
    }, 
 

 
    isImageFile: function (file) { 
 
     if (file.type) { 
 
     return /^image\/\w+$/.test(file.type); 
 
     } else { 
 
     return /\.(jpg|jpeg|png|gif)$/.test(file); 
 
     } 
 
    }, 
 

 
    startCropper: function() { 
 
     var _this = this; 
 

 
     if (this.active) { 
 
     this.$img.cropper('replace', this.url); 
 
     } else { 
 
     this.$img = $('<img src="' + this.url + '">'); 
 
     this.$avatarWrapper.empty().html(this.$img); 
 
     this.$img.cropper({ 
 
      aspectRatio: 1, 
 
      preview: this.$avatarPreview.selector, 
 
      crop: function (e) { 
 
      var json = [ 
 
        '{"x":' + e.x, 
 
        '"y":' + e.y, 
 
        '"height":' + e.height, 
 
        '"width":' + e.width, 
 
        '"rotate":' + e.rotate + '}' 
 
       ].join(); 
 

 
      _this.$avatarData.val(json); 
 
      } 
 
     }); 
 

 
     this.active = true; 
 
     } 
 

 
     this.$avatarModal.one('hidden.bs.modal', function() { 
 
     _this.$avatarPreview.empty(); 
 
     _this.stopCropper(); 
 
     }); 
 
    }, 
 

 
    stopCropper: function() { 
 
     if (this.active) { 
 
     this.$img.cropper('destroy'); 
 
     this.$img.remove(); 
 
     this.active = false; 
 
     } 
 
    }, 
 

 
    ajaxUpload: function() { 
 
     var url = this.$avatarForm.attr('action'); 
 
     var data = new FormData(this.$avatarForm[0]); 
 
     var _this = this; 
 

 
     $.ajax(url, { 
 
     type: 'post', 
 
     data: data, 
 
     dataType: 'json', 
 
     processData: false, 
 
     contentType: false, 
 

 
     beforeSend: function() { 
 
      _this.submitStart(); 
 
     }, 
 

 
     success: function (data) { 
 
      _this.submitDone(data); 
 
     }, 
 

 
     error: function (XMLHttpRequest, textStatus, errorThrown) { 
 
      _this.submitFail(textStatus || errorThrown); 
 
     }, 
 

 
     complete: function() { 
 
      _this.submitEnd(); 
 
     } 
 
     }); 
 
    }, 
 

 
    syncUpload: function() { 
 
     this.$avatarSave.click(); 
 
    }, 
 

 
    submitStart: function() { 
 
     this.$loading.fadeIn(); 
 
    }, 
 

 
    submitDone: function (data) { 
 
     console.log(data); 
 

 
     if ($.isPlainObject(data) && data.state === 200) { 
 
     if (data.result) { 
 
      this.url = data.result; 
 

 
      if (this.support.datauri || this.uploaded) { 
 
      this.uploaded = false; 
 
      this.cropDone(); 
 
      } else { 
 
      this.uploaded = true; 
 
      this.$avatarSrc.val(this.url); 
 
      this.startCropper(); 
 
      } 
 

 
      this.$avatarInput.val(''); 
 
     } else if (data.message) { 
 
      this.alert(data.message); 
 
     } 
 
     } else { 
 
     this.alert('Failed to response'); 
 
     } 
 
    }, 
 

 
    submitFail: function (msg) { 
 
     this.alert(msg); 
 
    }, 
 

 
    submitEnd: function() { 
 
     this.$loading.fadeOut(); 
 
    }, 
 

 
    cropDone: function() { 
 
     this.$avatarForm.get(0).reset(); 
 
     this.$avatar.attr('src', this.url); 
 
     this.stopCropper(); 
 
     this.$avatarModal.modal('hide'); 
 
    }, 
 

 
    alert: function (msg) { 
 
     var $alert = [ 
 
      '<div class="alert alert-danger avatar-alert alert-dismissable">', 
 
       '<button type="button" class="close" data-dismiss="alert">&times;</button>', 
 
       msg, 
 
      '</div>' 
 
      ].join(''); 
 

 
     this.$avatarUpload.after($alert); 
 
    } 
 
    }; 
 

 
    $(function() { 
 
    return new CropAvatar($('#crop-avatar')); 
 
    }); 
 

 
});

Это index.html

<!doctype html> 
 
<html lang="en"> 
 

 
<head> 
 
    <meta charset="utf-8"> 
 
    <meta http-equiv="x-ua-compatible" content="ie=edge"> 
 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
 
    <meta name="description" content="A complete example of Cropper."> 
 
    <meta name="keywords" content="HTML, CSS, JS, JavaScript, jQuery plugin, image cropping, image crop, image move, image zoom, image rotate, image scale, front-end, frontend, web development"> 
 
    <meta name="author" content="Fengyuan Chen"> 
 
    <title>Cropper</title> 
 
    <link rel="stylesheet" href="../../assets/css/bootstrap.min.css"> 
 
    <link rel="stylesheet" href="../../dist/cropper.min.css"> 
 
    <link rel="stylesheet" href="css/main.css"> 
 

 
    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> 
 
    <!--[if lt IE 9]> 
 
    <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> 
 
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> 
 
    <![endif]--> 
 
</head> 
 

 
<body> 
 
    <div class="container" id="crop-avatar"> 
 

 
    <!-- Current avatar --> 
 
    <div class="avatar-view" title="Change the avatar"> 
 
     <img src="img/picture.jpg" alt="Avatar"> 
 
    </div> 
 

 
    <!-- Cropping modal --> 
 
    <div class="modal fade" id="avatar-modal" aria-hidden="true" aria-labelledby="avatar-modal-label" role="dialog" tabindex="-1"> 
 
     <div class="modal-dialog modal-lg"> 
 
     <div class="modal-content"> 
 
      <form class="avatar-form" action="crop.php" enctype="multipart/form-data" method="post"> 
 
      <div class="modal-header"> 
 
       <button type="button" class="close" data-dismiss="modal">&times;</button> 
 
       <h4 class="modal-title" id="avatar-modal-label">Change Avatar</h4> 
 
      </div> 
 
      <div class="modal-body"> 
 
       <div class="avatar-body"> 
 

 
       <!-- Upload image and data --> 
 
       <div class="avatar-upload"> 
 
        <input type="hidden" class="avatar-src" name="avatar_src"> 
 
        <input type="hidden" class="avatar-data" name="avatar_data"> 
 
        <label for="avatarInput">Local upload</label> 
 
        <input type="file" class="avatar-input" id="avatarInput" name="avatar_file"> 
 
       </div> 
 

 
       <!-- Crop and preview --> 
 
       <div class="row"> 
 
        <div class="col-md-9"> 
 
        <div class="avatar-wrapper"></div> 
 
        </div> 
 
        <div class="col-md-3"> 
 
        <div class="avatar-preview preview-lg"></div> 
 
        <div class="avatar-preview preview-md"></div> 
 
        <div class="avatar-preview preview-sm"></div> 
 
        </div> 
 
       </div> 
 

 
       <div class="row avatar-btns"> 
 
        <div class="col-md-9"> 
 
        <div class="btn-group"> 
 
         <button type="button" class="btn btn-primary" data-method="rotate" data-option="-90" title="Rotate -90 degrees">Rotate Left</button> 
 
         <button type="button" class="btn btn-primary" data-method="rotate" data-option="-15">-15deg</button> 
 
         <button type="button" class="btn btn-primary" data-method="rotate" data-option="-30">-30deg</button> 
 
         <button type="button" class="btn btn-primary" data-method="rotate" data-option="-45">-45deg</button> 
 
        </div> 
 
        <div class="btn-group"> 
 
         <button type="button" class="btn btn-primary" data-method="rotate" data-option="90" title="Rotate 90 degrees">Rotate Right</button> 
 
         <button type="button" class="btn btn-primary" data-method="rotate" data-option="15">15deg</button> 
 
         <button type="button" class="btn btn-primary" data-method="rotate" data-option="30">30deg</button> 
 
         <button type="button" class="btn btn-primary" data-method="rotate" data-option="45">45deg</button> 
 
        </div> 
 
        </div> 
 
        <div class="col-md-3"> 
 
        <button type="submit" class="btn btn-primary btn-block avatar-save">Done</button> 
 
        </div> 
 
       </div> 
 
       </div> 
 
      </div> 
 
      <!-- <div class="modal-footer"> 
 
       <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> 
 
      </div> --> 
 
      </form> 
 
     </div> 
 
     </div> 
 
    </div> 
 
    <!-- /.modal --> 
 

 
    <!-- Loading state --> 
 
    <div class="loading" aria-label="Loading" role="img" tabindex="-1"></div> 
 
    </div> 
 

 
    <script src="../../assets/js/jquery.min.js"></script> 
 
    <script src="../../assets/js/bootstrap.min.js"></script> 
 
    <script src="../../dist/cropper.min.js"></script> 
 
    <script src="js/main.js"></script> 
 
</body> 
 

 
</html>

+0

Пожалуйста, включите соответствующие части кода в вопрос. Благодарю. –

+0

@ Николас я сделал. спасибо – user3856362

+0

Хорошо, хорошо, но в качестве модератора я бы сказал, что это выглядит как больше кода, чем вам нужно задать вопрос. Лучше как для вас, так и для людей, которые смотрят на ваш вопрос, если вы можете уменьшить его, чтобы точно решить проблему. Это лучше для вас, потому что вы можете ответить на свой вопрос, прежде чем публиковать его, лучше для других, потому что им не нужно это делать для вас и кто хочет помочь с кодом, который вы, возможно, просто скопировали из другого места? Благодарю. –

ответ

-1

следующий код, чтобы изменить значение по умолчанию -> подробнее см read.me файл @https://github.com/fengyuanchen/cropper.

<script type="text/javascript"> 

    $.fn.cropper.setDefaults(
     { 
     aspectRatio: 1, //// or 1.7777777777 (16/9) or any positive nubmer 
     }); 

    </script> 
+0

Это действительно не работает для меня – Monclee

0
<script type="text/javascript"> 

    // initial set up 
    var $image = $('.cropper > img'); 
    var options = { 
     aspectRatio: 16/9, // (1.7777) 
     etc..., 
     etc... 
    }; 

    // initialize 
    $image.cropper(options); 

    // toggle aspect ratio after initialization 
    $(document).on('click', '#toggle-aspect-ratio .btn', function() { 
     options.aspectRatio = $(this).attr('data-value'); 
     $image.cropper('destroy').cropper(options); 
    }); 


</script> 

<div id="toggle-aspect-ratio"> 
    <span class="btn" data-value="NaN">Freeform</span> 
    <span class="btn" data-value="1.77777">16/9</span> 
    <span class="btn" data-value="1.33333">4/3</span> 
</div> 

Примечание: $ (это) .attr ('данных значение') (или любой другой) должен быть номер/десятичную (например: 1,33333) и не строка (например: 4/3), или он будет читать как NaN.