(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('jquery')) : typeof define === 'function' && define.amd ? define(['jquery'], factory) : (factory(global.$)); }(this, (function ($) { 'use strict'; $ = 'default' in $ ? $['default'] : $; var DEFAULTS = { // Define the view mode of the cropper viewMode: 0, // 0, 1, 2, 3 显示 // Define the dragging mode of the cropper dragMode: 'crop', // 'crop', 'move' or 'none' // Define the aspect ratio of the crop box aspectRatio: NaN, // An object with the previous cropping result data data: null, // A selector for adding extra containers to preview preview: '', // Re-render the cropper when resize the window responsive: true, // Restore the cropped area after resize the window restore: true, // Check if the current image is a cross-origin image checkCrossOrigin: true, // Check the current image's Exif Orientation information checkOrientation: true, // Show the black modal modal: true, // Show the dashed lines for guiding guides: true, // Show the center indicator for guiding center: true, // Show the white modal to highlight the crop box highlight: true, // Show the grid background background: true, // Enable to crop the image automatically when initialize autoCrop: true, // Define the percentage of automatic cropping area when initializes autoCropArea: 0.8, // Enable to move the image movable: true, // Enable to rotate the image rotatable: true, // Enable to scale the image scalable: true, // Enable to zoom the image zoomable: true, // Enable to zoom the image by dragging touch zoomOnTouch: true, // Enable to zoom the image by wheeling mouse zoomOnWheel: true, // Define zoom ratio when zoom the image by wheeling mouse wheelZoomRatio: 0.1, // Enable to move the crop box cropBoxMovable: true, // Enable to resize the crop box cropBoxResizable: true, // Toggle drag mode between "crop" and "move" when click twice on the cropper toggleDragModeOnDblclick: true, // Size limitation minCanvasWidth: 0, minCanvasHeight: 0, minCropBoxWidth: 0, minCropBoxHeight: 0, minContainerWidth: 200, minContainerHeight: 100, // Shortcuts of events ready: null, cropstart: null, cropmove: null, cropend: null, crop: null, zoom: null };
main.js 代码如下:
$(function () { 'use strict';//表示强规则 var console = window.console || { log: function () {} }; var URL = window.URL || window.webkitURL; var $image = $('#image'); var $download = $('#download'); //获取图片截取的位置 var $dataX = $('#dataX'); var $dataY = $('#dataY'); var $dataHeight = $('#dataHeight'); var $dataWidth = $('#dataWidth'); var $dataRotate = $('#dataRotate'); var $dataScaleX = $('#dataScaleX'); var $dataScaleY = $('#dataScaleY'); var options = { aspectRatio: 1 / 1, //裁剪框比例1:1 preview: '.img-preview', crop: function (e) { $dataX.val(Math.round(e.x)); $dataY.val(Math.round(e.y)); $dataHeight.val(Math.round(e.height)); $dataWidth.val(Math.round(e.width)); $dataRotate.val(e.rotate); $dataScaleX.val(e.scaleX); $dataScaleY.val(e.scaleY); } }; var originalImageURL = $image.attr('src'); var uploadedImageURL; // Tooltip $('[data-toggle="tooltip"]').tooltip(); // Cropper $image.on({ ready: function (e) { console.log(e.type); }, cropstart: function (e) { console.log(e.type, e.action); }, cropmove: function (e) { console.log(e.type, e.action); }, cropend: function (e) { console.log(e.type, e.action); }, crop: function (e) { console.log(e.type, e.x, e.y, e.width, e.height, e.rotate, e.scaleX, e.scaleY); }, zoom: function (e) { console.log(e.type, e.ratio); } }).cropper(options); // Buttons if (!$.isFunction(document.createElement('canvas').getContext)) { $('button[data-method="getCroppedCanvas"]').prop('disabled', true); } if (typeof document.createElement('cropper').style.transition === 'undefined') { $('button[data-method="rotate"]').prop('disabled', true); $('button[data-method="scale"]').prop('disabled', true); } // Download if (typeof $download[0].download === 'undefined') { $download.addClass('disabled'); } // Options $('.docs-toggles').on('change', 'input', function () { var $this = $(this); var name = $this.attr('name'); var type = $this.prop('type'); var cropBoxData; var canvasData; if (!$image.data('cropper')) { return; } if (type === 'checkbox') { options[name] = $this.prop('checked'); cropBoxData = $image.cropper('getCropBoxData'); canvasData = $image.cropper('getCanvasData'); options.ready = function () { $image.cropper('setCropBoxData', cropBoxData); $image.cropper('setCanvasData', canvasData); }; } else if (type === 'radio') { options[name] = $this.val(); } $image.cropper('destroy').cropper(options); }); // Methods // 点击开始计算图片位置,获取位置 $('.docs-buttons').on('click', '[data-method]', function () { var $this = $(this); var data = $this.data(); var $target; var result; if ($this.prop('disabled') || $this.hasClass('disabled')) { return; } if ($image.data('cropper') && data.method) { data = $.extend({}, data); // Clone a new one if (typeof data.target !== 'undefined') { $target = $(data.target); if (typeof data.option === 'undefined') { try { data.option = JSON.parse($target.val()); } catch (e) { console.log(e.message); } } } if (data.method === 'rotate') { $image.cropper('clear'); } result = $image.cropper(data.method, data.option, data.secondOption); if (data.method === 'rotate') { $image.cropper('crop'); } switch (data.method) { case 'scaleX': case 'scaleY': $(this).data('option', -data.option); break; case 'getCroppedCanvas': //上传头像 if (result) { var imgBase=result.toDataURL('image/jpeg'); var data={imgBase:imgBase}; $.post('/docs/upload.php',data,function(ret){ if(ret=='true'){ alert('上传成功'); }else{ alert('上传失败'); } },'text'); } break; case 'destroy': if (uploadedImageURL) { URL.revokeObjectURL(uploadedImageURL); uploadedImageURL = ''; $image.attr('src', originalImageURL); } break; } if ($.isPlainObject(result) && $target) { try { $target.val(JSON.stringify(result)); } catch (e) { console.log(e.message); } } } }); // Keyboard $(document.body).on('keydown', function (e) { if (!$image.data('cropper') || this.scrollTop > 300) { return; } switch (e.which) { case 37: e.preventDefault(); $image.cropper('move', -1, 0); break; case 38: e.preventDefault(); $image.cropper('move', 0, -1); break; case 39: e.preventDefault(); $image.cropper('move', 1, 0); break; case 40: e.preventDefault(); $image.cropper('move', 0, 1); break; } }); // Import image var $inputImage = $('#inputImage'); if (URL) { $inputImage.change(function () { var files = this.files; var file; if (!$image.data('cropper')) { return; } if (files && files.length) { file = files[0]; if (/^image\/\w+$/.test(file.type)) { if (uploadedImageURL) { URL.revokeObjectURL(uploadedImageURL); } uploadedImageURL = URL.createObjectURL(file); $image.cropper('destroy').attr('src', uploadedImageURL).cropper(options); $inputImage.val(''); } else { window.alert('Please choose an image file.'); } } }); } else { $inputImage.prop('disabled', true).parent().addClass('disabled'); } });
使用canvas生成的截图转换生成base64代码。
后台处理base64代码片段(PHP服务端)。
upload.php代码如下: