最近要做一个照片裁剪功能。就选用了cropper.js
代码如下:贴出来
<div class="container">
<div class="row">
<div class="col col-6">
<img id="image" src="${dcutpic }" alt="Picture">
</div>
<div class="col col-4">
<div class="preview"></div>
</div>
</div>
</div>
<script type="text/javascript">
$(function () {
// $('#image').cropper('setData',{width:'400px',
// height:'300px'});
var $previews = $('.preview');
$('#image').cropper({
//preview: ".preview",
//
ready: function (e) {
$(this).cropper('reset');
var $clone = $(this).clone().removeClass('cropper-hidden');
console.log($clone);
$clone.css({
display: 'block',
width: '100%',
minWidth: 0,
minHeight: 0,
maxWidth: 'none',
maxHeight: 'none'
});
$previews.css({
width: '263'
}).html($clone);
var previewWidth = $previews.width();
console.log(previewWidth);
},
crop: function (e) {
var imageData = $(this).cropper('getImageData');
console.log(2354);
console.log(imageData);
var previewAspectRatio = e.width / e.height;
console.log(previewAspectRatio);
var previewWidth = $previews.width();
console.log(previewWidth);
var previewHeight = previewWidth / previewAspectRatio;
var imageScaledRatio = e.width / previewWidth;
$previews.height(previewHeight).find('img').css({
width: imageData.naturalWidth / imageScaledRatio,
height: imageData.naturalHeight / imageScaledRatio,
marginLeft: -e.x / imageScaledRatio,
marginTop: -e.y / imageScaledRatio
});
canvas=$('#image').cropper('getCroppedCanvas',{fillColor: '#fff',
imageSmoothingEnabled: false,
imageSmoothingQuality: 'high'});
console.log(canvas);
console.log(convertCanvasToImage(canvas));
},
minContainerWidth:400
});
$('#image').cropper('scale', 1);
});
//canvas转换图片
function convertCanvasToImage(canvas) {
var image = new Image();
image.src = canvas.toDataURL("image/png");
return image;
}
最后一步是直接将转化后的图片插入到div里面
$('#carPhoto').empty().append(convertCanvasToImage(canvas));
至此就结束了。