利用Javascript裁剪图片并存储的简单实现

前言

就我而言,页面上的设计比较灵动的部分,其实不是很多,诸如滑动验证码,图片裁剪等比较好的交互设计。

从刚开始工作的时候,我就想把这些东西了解下,无奈一直没这个需求,乘着今天的空闲,研究了一下午,期间遇到了大大小小的问题,一直备受折磨,这其实也反映一个问题,我的

还是比较薄弱。

实现效果:

用户点击上传图片后,页面显示所上传的图片,并且出现裁剪框和两个预览区域,最后点击裁剪按钮保存裁剪的图片到服务器上。

效果很简单,整个过程我遇到的两个难点,第一个是裁剪的JS效果,第二个则是图片数据的处理。

对于第一个问题,我引用了网上的一个插件,就我感觉来说,裁剪过程用户的满意度只能算一般,因为它只能裁剪正方形区域,就算边框上有八个拉动设置,但是拉动框时还是按正方形缩放,就这点不太让我满意。

实现方法如下:

以下是简单的页面设计:

下面是JS代码:

var jcrop_api,boundx,boundy;

setTimeout(function(){

$('#target').Jcrop({
minSize: [48,48],setSelect: [0,190,190],onChange: updatePreview,onSelect: updatePreview,onSelect: updateCoords,aspectRatio: 1
},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;
});

function updatePreview(c){
if (parseInt(c.w) > 0)
{
var rx = 48 / c.w; //小头像预览Div的大小
var ry = 48 / c.h;

$('#preview').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'
});
}
{
var rx = 199 / c.w; //大头像预览Div的大小
var ry = 199 / c.h;
$('#preview2').css({
width: Math.round(rx boundx) + 'px',marginTop: '-' + Math.round(ry c.y) + 'px'
});
}
};

function updateCoords(c)
{
$('#x').val(c.x);
$('#y').val(c.y);
$('#w').val(c.w);
$('#h').val(c.h);
};

},500);

}

这里稍作两点提醒:

其一:不要忘记在页面头部引入插件: