在 Web 開發中,圖片裁剪是常見需求。雖然伺服器端(如 PHP GD 庫)可處理,但採用前端 JavaScript 實現可大幅提升用戶體驗,減少伺服器負載。本文將介紹一套基於 jQuery 的圖片裁剪元件,支援拖曳選區、八向縮放、即時預覽等功能。
裁剪元件主要包含兩個區域:
通過監聽滑鼠事件(mousedown、mousemove、mouseup),計算選區位置與尺寸,並同步更新預覽區的 background-position 實現即時預覽。
var clip = function(options) {
this.init.call(this, options);
};
clip.prototype = {
options: {
moveCallBack: function(){},
className: "block"
},
init: function(options) {
$.extend(this, this.options, options || {});
if (!this.container || !this.imgC) return;
this.container = $(this.container);
var self = this;
// 動態建立選區與 8 個控制點
this.block = $('<div class="' + this.className + '">' +
'<div action="rightDown" class="rRightDown"></div>' +
'<div action="leftDown" class="rLeftDown"></div>' +
'<div action="rightUp" class="rRightUp"></div>' +
'<div action="leftUp" class="rLeftUp"></div>' +
'<div action="right" class="rRight"></div>' +
'<div action="left" class="rLeft"></div>' +
'<div action="up" class="rUp"></div>' +
'<div action="down" class="rDown"></div>' +
'</div>')
.bind("mousedown.r", function(e) { self.start(e); })
.appendTo(this.container[0]);
this.setImg();
},
// ...
};
start 方法記錄初始座標與選區狀態,根據點擊目標(控制點或選區本身)決定是移動還是縮放:
start: function(e) {
var $elem = $(e.target),
action = $elem.attr("action");
this.offset = $.extend({
height: this.container.height(),
width: this.container.width()
}, this.container.offset());
this.blockOriginal = {
height: this.block.height(),
width: this.block.width(),
left: parseInt(this.block.css("left")),
top: parseInt(this.block.css("top"))
};
if (action) {
this.fun = this[action]; // 縮放處理函數
} else {
this.x = e.clientX - this.offset.left - this.blockOriginal.left;
this.y = e.clientY - this.offset.top - this.blockOriginal.top;
}
$(document)
.bind("mousemove.r", function(e) { self.move(e, !action); })
.bind("mouseup.r", function() { self.end(); });
}
move 方法確保選區不超出容器範圍,並呼叫 setImg() 更新預覽:
move: function(e, isMove) {
var block = this.block;
if (isMove) {
var left = Math.max(0, e.clientX - this.offset.left - this.x);
left = Math.min(left, this.offset.width - this.blockOriginal.width);
var top = Math.max(0, e.clientY - this.offset.top - this.y);
top = Math.min(top, this.offset.height - this.blockOriginal.height);
block.css({ left: left, top: top });
} else {
var offset = this.fun(e); // 呼叫對應的縮放函數
block.css(offset);
}
this.setImg();
this.moveCallBack();
},
setImg: function() {
var block = this.block;
this.imgC.css({
height: block.height(),
width: block.width(),
"background-position": "-" + block.css("left") + " -" + block.css("top")
});
}
每個控制點對應一個處理函數(rightDown、leftUp 等),根據滑鼠位置計算新的寬高與座標。以右下角為例:
rightDown: function(e) {
var blockOriginal = this.blockOriginal,
offset = this.offset;
var width = Math.min(offset.width - blockOriginal.left,
e.clientX - offset.left - blockOriginal.left);
var height = Math.min(offset.height - blockOriginal.top,
e.clientY - offset.top - blockOriginal.top);
return { width: width, height: height };
}
其他方向同理,需處理座標系轉換與邊界條件。
new clip({
container: "#container", // 原圖容器
imgC: "#imgC", // 預覽容器
className: "block", // 選區 class
moveCallBack: function() { /* 裁剪時的回調 */ }
});
這套元件展示了原生 JavaScript 結合 jQuery 實現複雜互動的經典模式:
現代專案可考慮使用 Cropper.js 等成熟庫,但理解底層邏輯有助於客製化開發。