最近在写项目的过程中,需要用到图像裁切上传,所以接触了插件jcrop。这个插件的裁切功能主要是获取裁切图片后的x坐标,y坐标与裁切图片的宽度和高度。该插件运行后,dom格式如下
关于该插件的源码,以及源码中的中文注释部分已发布到github 源码解析
这里说一下主要用法
首先需要引入jquery库和jcrop插件
<script type="text/javascript" src="src/jquery.min.js"></script>
<script type="text/javascript" src="src/jquery.Jcrop.js"></script>
添加dom节点
初始化jcrop
<script type="text/javascript">
$(document).ready(function(){
var api = $.Jcrop("#img",{
boxWidth:200,//图片的最大宽度
boxHeight:200,//图片的最大高度
onChange:showPreview,//选区改变时触发的事件
onSelect:showPreview,
aspectRatio:1//设定宽高比为1
})
console.log(api);
//设定初始选框的大小和位置,参数为数组形式 分别为左上角的x、y 右下角的x y
api.setSelect([$("#img").width()>$("#img").height()?1/2*($("#img").width()-$("#img").height()):0, $("#img").width()>$("#img").height()?0:1/2*($("#img").height()-$("#img").width()), $("#img").width()>$("#img").height()?1/2*($("#img").width()+$("#img").height()):$("#img").height(), $("#img").width()>$("#img").height()?$("#img").height():1/2*($("#img").height()+$("#img").width())]);
function showPreview(coords){
console.log(coords);
if(parseInt(coords.w)>0){
var rx = $("#pre_box").width()/coords.w;
var ry = $("#pre_box").height()/coords.h;
$("#crop_pre").css({
width:Math.round(rx*$("#img").width())+"px",
height:Math.round(ry*$("#img").height())+"px",
marginLeft:"-"+Math.round(rx*coords.x)+"px",
marginTop:"-"+Math.round(ry*coords.y)+"px"
})
}
}
})
</script>
当运行程序时 初始化状态为
缩略图状态为