Jcrop 是一款知名的 jQuery 圖片裁剪外掛,可讓使用者在畫面上框選裁剪範圍。以下整理它的基本用法、options 參數與 API 方法,方便查閱。
<link rel="stylesheet" href="css/jquery.Jcrop.css">
<script src="js/jquery.js"></script>
<script src="js/jquery.Jcrop.js"></script>
<script language="Javascript">
jQuery(function($){
var jcrop_api, boundx, boundy;
$('#cropbox').Jcrop({
minSize: [0,0],
maxSize:[0,0],
setSelect: [0,0,0,0],
boxWidth:800,
borderOpacity:0.3,
keySupport:false,
dragEdges:false,
allowSelect:false,
allowResize:false,
bgOpacity:0.2,
boundary:0,
addClass: 'jcrop-handle',
onSelect: updateCoords,
},
function(){
var bounds = this.getBounds();
boundx = bounds[0];
boundy = bounds[1];
jcrop_api = this;
});
function updateCoords(c) {
$('#x').val(c.x);
$('#y').val(c.y);
$('#w').val(c.w);
$('#h').val(c.h);
};
function checkCoords() {
if (parseInt($('#w').val())) return true;
alert('請選擇裁剪區域');
return false;
};
});
</script>
<img id="cropbox" src="x.jpg">
如此便能實現最簡單的裁剪效果。至於如何結合 PHP 等後端語言處理圖片,可參考作者的置頂範例文章。
setImage(string):設定或改變圖像,例如 jcrop_api.setImage("newpic.jpg")。setOptions(object):設定或改變參數。setSelect(array):建立選框,格式為 [x, y, x2, y2]。animateTo(array):以動畫建立選框。release():取消選框。disable()/enable():停用或啟用 Jcrop。destroy():移除 Jcrop。tellSelect()/tellScaled():取得選框的實際尺寸或顯示尺寸。getBounds():取得圖片實際尺寸 [w, h]。getWidgetSize():取得圖片顯示尺寸 [w, h]。getScaleFactor():取得圖片縮放比例 [w, h]。掌握這些參數與方法,就能靈活客製各種裁剪互動了。