做网页开发少不了就是头像上传,但是我们并不希望用户选择多大的图片就有多大,那么服务器吃不消的。我们需要用户自己裁剪头像到程序固定的大小。就介绍一款我非常喜欢的插件cropbox.js,如果还在纠结怎么弄?那么看这篇文章就对了!咳咳咳~~~源码里面有很多美图哦
3087014508.png
首先肯定需要导入需要的插件cropbox.js
然后需要一个上传的按钮
缩小、放大、裁剪按钮,不用说了吧。
现在就是js代码了,和运用cropbox.js
1.上传头像事件
var options =
{
thumbBox: '.thumbBox',
spinner: '.spinner',
imgSrc: 'img/5.jpg'
}
var cropper = $('.imageBox').cropbox(options);
$('#upload-file').on('change', function()
{
var reader = new FileReader();
reader.onload = function(e) {
options.imgSrc = e.target.result;
cropper = $('.imageBox').cropbox(options);
}
reader.readAsDataURL(this.files[0]);
this.files = [];
})
2.裁剪
$('#btnCrop').on('click', function(){
var img = cropper.getDataURL();
$('.cropped').html('');
$('.cropped').append('![]('+img+')
64px*64px
');$('.cropped').append('![]('+img+')
128px*128px
');$('.cropped').append('![]('+img+')
180px*180px
');})
3.缩放
$('#btnZoomIn').on('click', function(){
cropper.zoomIn();
})
$('#btnZoomOut').on('click', function(){
cropper.zoomOut();
})
都是很简单的代码。注意,所有图片数据都是Base64编码。
完整js代码
$(window).load(function() {
var options =
{
thumbBox: '.thumbBox',
spinner: '.spinner',
imgSrc: 'img/5.jpg'
}
var cropper = $('.imageBox').cropbox(options);
$('#upload-file').on('change', function(){
var reader = new FileReader();
reader.onload = function(e) {
options.imgSrc = e.target.result;
cropper = $('.imageBox').cropbox(options);
}
reader.readAsDataURL(this.files[0]);
this.files = [];
})
$('#btnCrop').on('click', function(){
var img = cropper.getDataURL();
$('.cropped').html('');
$('.cropped').append('![]('+img+')
64px*64px
');$('.cropped').append('![]('+img+')
128px*128px
');$('.cropped').append('![]('+img+')
180px*180px
');})
$('#btnZoomIn').on('click', function(){
cropper.zoomIn();
})
$('#btnZoomOut').on('click', function(){
cropper.zoomOut();
})
});