學 PHP GD 函式庫時看到圖片裁剪的功能,於是順手做了一個前端的選取介面。其實原理不複雜:讓使用者拖動一個框,框的位置與尺寸就是要裁剪的區域。
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Resize</title>
<style type="text/css">
* { padding: 0; margin: 0; }
ul { list-style-type: none; overflow: hidden; zoom: 1; width: 1000px; margin: 30px auto; }
li { float: left; width: 500px; }
#container {
width: 480px; height: 480px; margin: 0 auto;
border: 1px solid #999; position: relative;
background: url(https://images.cnblogs.com/cnblogs_com/wtcsy/192373/r_xx.jpg);
}
#container .block {
height: 100px; width: 100px;
border: 1px solid #000000;
position: absolute; left: 50px; top: 50px;
background: #fff; filter: alpha(opacity=30); opacity: 0.3;
cursor: move;
}
/* 八個縮放控制點 */
.rRightDown, .rLeftDown, .rLeftUp, .rRightUp,
.rRight, .rLeft, .rUp, .rDown {
position: absolute; background: #f00;
width: 6px; height: 6px; z-index: 5; font-size: 0;
}
.rLeftDown, .rRightUp { cursor: ne-resize; }
.rRightDown, .rLeftUp { cursor: nw-resize; }
.rRight, .rLeft { cursor: e-resize; }
.rUp, .rDown { cursor: n-resize; }
.rRightDown { bottom: -3px; right: -3px; }
.rLeftDown { bottom: -3px; left: -3px; }
.rRightUp { top: -3px; right: -3px; }
.rLeftUp { top: -3px; left: -3px; }
.rRight { right: -3px; top: 50%; }
.rLeft { left: -3px; top: 50%; }
.rUp { top: -3px; left: 50%; }
.rDown { bottom: -3px; left: 50%; }
#imgC {
border: 1px solid #CCC; width: 0; height: 0; margin: 0 auto;
background: url(https://images.cnblogs.com/cnblogs_com/wtcsy/192373/r_xx.jpg);
}
</style>
</head>
<body>
<ul>
<li><div id="container"></div></li>
<li><div id="imgC"></div></li>
</ul>
版面是左右兩欄:左邊是原圖加半透明裁切框,右邊是即時預覽的裁剪結果。
幾個 CSS 細節值得注意:八個縮放點用 -3px 的負偏移讓 6×6 的小方塊有一半懸在裁切框外,視覺上更精準;cursor 依方向分別設為 ne-resize、nw-resize、e-resize、n-resize,給使用者正確的操作暗示;filter: alpha(opacity=30) 是 IE 專屬寫法,需搭配 opacity: 0.3 才能跨瀏覽器。
<script type="text/javascript" src="https://common.cnblogs.com/script/jquery.js"></script>
<script type="text/javascript">
(function () {
var dBody = document.body,
dDoc = document.documentElement;
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;
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();
},
setImg: function () {
var block = this.block;
this.imgC.css({
height: block.height(),
width: block.width(),
"background-position": "-" + block.css("left") + " -" + block.css("top")
});
},
setImg 是預覽同步的關鍵,也是整個實作最巧妙的地方:它並沒有真的裁剪圖片,而是用 background-position 做視覺偏移。
右側的 #imgC 使用與原圖相同的背景圖片,尺寸等於裁切框,再把背景位置設為 -left -top。這樣在預覽框裡看到的,就正好是裁切框位置與尺寸的那塊區域。完全不需要 canvas,也不耗任何額外頻寬。
start: function (e) {
var $elem = $(e.target),
block = this.block,
self = this,
move = false,
container = this.container,
action = $elem.attr("action");
// 這個每次都重新計算,因為基本 DOM 結構的改變、
// 瀏覽器的縮放都會讓裡面的值發生改變
this.offset = $.extend({
height: container.height(),
width: container.width()
}, container.offset());
this.blockOriginal = {
height: block.height(),
width: block.width(),
left: parseInt(block.css("left")),
top: parseInt(block.css("top"))
};
if (action) {
this.fun = this[action]; // 點在縮放控制點上,走 resize
} else {
this.x = e.clientX - this.offset.left - this.blockOriginal.left;
this.y = e.clientY - this.offset.top - this.blockOriginal.top;
move = true; // 點在框內,走 move
}
$(document)
.bind("mousemove.r", function (e) { self.move(e, move); })
.bind("mouseup.r", function () { self.end(); });
},
end: function () {
$(document)
.unbind("mousemove.r")
.unbind("mouseup.r");
},
move: function (e, isMove) {
window.getSelection
? window.getSelection().removeAllRanges()
: document.selection.empty();
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();
},
幾個關鍵設計:
每次 mousedown 都重新計算 offset 與 blockOriginal。註解說明了原因:DOM 結構變動、視窗縮放、頁面捲動都可能改變這些值,快取起來反而危險。
mousemove 與 mouseup 綁在 document 而非 block 上。這樣滑鼠移出裁切框後拖動仍然連續,不會中斷。這比原作者另一篇拖拽文章的做法更穩健。
用 action 屬性分派行為。八個縮放點各自帶一個 action 值(rightDown、left……),start 時讀出來對應到同名方法。這比寫八個 if-else 乾淨得多。
移動時用 Math.max / Math.min 做邊界夾制。先確保 left 不小於 0,再確保它不大於「容器寬減去自身寬」,裁切框 therefore 永遠不會跑出容器。
事件命名空間 .r。bind("mousemove.r", ...) 這種寫法讓 unbind 時可以精準解除,不影響同一事件上的其他處理器。這是很值得學的細節。
每個方向的方法都回傳要套用的樣式物件。以 down 為例:
down: function (e) {
var blockOriginal = this.blockOriginal,
sTop = Math.max(dBody.scrollTop, dDoc.scrollTop), // 出現垂直捲軸時要計算
offset = this.offset;
if (e.clientY - offset.top >= blockOriginal.top - sTop) {
var height = Math.min(
offset.height - blockOriginal.top,
e.clientY - offset.top - blockOriginal.top + sTop
), top = blockOriginal.top;
} else {
var height = Math.min(
offset.top + blockOriginal.top - e.clientY - sTop,
blockOriginal.top
), top = Math.max(e.clientY - offset.top + sTop, 0);
}
return { height: height, top: top };
},
這裡處理的是一個容易忽略的情況:往下拖時 top 不變、height 增大;但若滑鼠越過了裁切框的上邊界,就必須轉為「往上推 top、同時縮小 height」。少了這個判斷,往上越界時裁切框會出現負高度。
sTop 的計算(取 body 與 documentElement 的 scrollTop 較大值)是為了處理頁面捲動時 clientY 與頁面座標的落差。
四角的做法是把兩個邊的方法結果合併:
rightDown: function (e) {
return $.extend(this.right(e), this.down(e));
},
leftDown: function (e) {
return $.extend(this.left(e), this.down(e));
},
rightUp: function (e) {
return $.extend(this.right(e), this.up(e));
},
leftUp: function (e) {
return $.extend(this.left(e), this.up(e));
},
getValue: function () {
var block = this.block;
return {
left: parseInt(block.css("left")),
top: parseInt(block.css("top")),
width: block.width(),
height: block.height()
};
}
};
$.fn.clip = function (options) {
options.container = this;
return new clip(options);
};
})();
$("#container").clip({
imgC: $("#imgC")
});
</script>
</body>
</html>
getValue() 回傳最終的裁剪座標,可以直接送到後端給 GD 或 ImageMagick 裁圖。
$.fn.clip 把它包成 jQuery 插件形式,呼叫端只需一行 $("#container").clip({ imgC: $("#imgC") }),並可透過 moveCallBack 回呼監聽變化。
這份實作完成度高,但仍有幾處值得調整。
拖動時應改用 transform。改動 left / top 會觸發 reflow,而 transform: translate() 只走合成層。搭配 requestAnimationFrame 能進一步對齊繪製週期,拖動會順很多。
選取清除的相容寫法。document.selection.empty() 是 IE 專屬且已棄用,現代瀏覽器一律走 window.getSelection().removeAllRanges()。更好的做法是解掉這個問題的根源:在 CSS 上對容器加 user-select: none。
固定比例的裁切。實務上頭像裁剪往往需要固定 1:1。這可以在 move 與 resize 中加上比例約束:調整完一邊後,用邊長反推另一邊。
觸控支援。原實作只有 mouse 事件,行動裝置上完全不能用。需要同時綁 touchstart / touchmove / touchend,並在 CSS 上加 touch-action: none 阻止頁面跟手滾動。
無障礙。純滑鼠操作的元件對鍵盤使用者完全不可用。應為裁切框加上 tabindex="0" 與方向鍵控制,並透過 ARIA 屬性標示當前位置與尺寸。
若要在新專案中實作,建議直接用成熟套件:Cropper.js 與 react-easy-crop 都完整處理了觸控、縮放、固定比例、鍵盤操作與 canvas 輸出,這些邊界情況自己寫的成本遠高於引入依賴。