onChange、onSelect、onReleasesetSelect、animateTo、release、disable/enable、setImagewebapp/
├── css/
│ ├── jquery.Jcrop.css
│ └── jquery.Jcrop.extras.css
├── js/
│ ├── jquery.min.js
│ ├── jquery.Jcrop.js
│ └── jquery.color.js (動畫顏色漸變需引入)
└── demo_files/ (示例圖片)
頁面引入順序:jQuery → Jcrop JS → Jcrop CSS → extras CSS (可選)
$('#target').Jcrop();
默認行為:自由拖拽選區,無回調,無預覽。
$('#target').Jcrop({
onChange: updateCoords,
onSelect: updateCoords,
onRelease: clearCoords
});
function updateCoords(c) {
$('#x1').val(c.x); $('#y1').val(c.y);
$('#x2').val(c.x2); $('#y2').val(c.y2);
$('#w').val(c.w); $('#h').val(c.h);
}
function clearCoords() { $('input', '#coords').val(''); }
典型用於頭像上傳前端預填裁剪參數。
var api, boundx, boundy;
$('#target').Jcrop({
onChange: updatePreview,
onSelect: updatePreview,
aspectRatio: 1 // 1:1
}, function() {
api = this;
var bounds = this.getBounds();
boundx = bounds[0]; boundy = bounds[1];
});
function updatePreview(c) {
if (c.w > 0) {
var rx = 100 / c.w, ry = 100 / 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'
});
}
}
預覽原理:同一張圖疊加,通過 margin 負值定位顯示選區內容。
$('#target').Jcrop({
bgFade: true, bgOpacity: 0.3,
setSelect: [60, 70, 540, 330]
}, function() { api = this; });
// 程序化動畫
$('#anim1').click(() => api.animateTo([217, 122, 382, 284]));
$('#anim2').click(() => api.animateTo([20, 20, 580, 380]));
需引入 jquery.color.js 支持背景顏色漸變。
setImage)aspectRatio、minSize/maxSizeallowSelect、allowMove、allowResize前端提交 x,y,x2,y2,w,h,後端(Java 示例):
BufferedImage src = ImageIO.read(new File(uploadPath));
BufferedImage cropped = src.getSubimage(x, y, w, h);
ImageIO.write(cropped, "jpg", new File(outputPath));
注意:前端圖片若經過 CSS 縮放顯示,**必須按原圖比例換算坐標**,或直接使用 Jcrop 返回的原圖坐標(getBounds() 輔助)。
onload 後再初始化 Jcropapi.destroy() 再重新 $('#target').Jcrop()Jcrop 雖已停止維護,但 API 成熟穩定,配合少量代碼即可構建專業級裁剪體驗。