本文簡介
點贊 + 關(guān)注 + 收藏 = 學(xué)會了
題目:
當(dāng)兩個元素有部分重疊時,選中底層元素后,想通過被蓋住的部分移動元素,該如何實現(xiàn)?

其實 Fabric.js 已經(jīng)提供了相應(yīng)的 API 去完成上面的需求了。但直到今天, Fabric.js 官方文檔還是那么晦澀難懂,于是就有了本文。
動手實現(xiàn)
先來看看默認(rèn)的效果

默認(rèn)情況下,被選中的元素會跑到視圖的最頂層,釋放后會恢復(fù)到原來的層級。
如果需要做到“本文簡介”提到的效果,需要將 preserveObjectStacking 設(shè)置為 true ,同時使用 altSelectionKey 指定組合鍵。
先看看官方文檔
preserveObjectStacking :Boolean
Indicates whether objects should remain in current stack position when selected. When false objects are brought to top and rendered as part of the selection group
將 preserveObjectStacking 設(shè)置為 true ,可以讓元素被選中時保留在原來的層級,我在 《Fabric.js 元素被選中時保持原有層級》 里也有提到過。
altSelectionKey :null|String
Indicates which key enable alternative selection in case of target overlapping with active object values: 'altKey', 'shiftKey', 'ctrlKey'. For a series of reason that come from the general expectations on how things should work, this feature works only for preserveObjectStacking true. If
nullor 'none' or any other string that is not a modifier key feature is disabled.
altSelectionKey 可以設(shè)置選中的組合鍵,可傳入 'altKey'、 'shiftKey'、 'ctrlKey' 三個值。分別對應(yīng)鍵盤上的 alt鍵、shift鍵、ctrl鍵。
如果傳入的是 'null'、'none' 或其他不相關(guān)的字符,就不采用任何功能鍵配合(當(dāng)沒事發(fā)生過)。
由于 Fabric.js 的默認(rèn)操作邏輯(前面演示過),在設(shè)置 altSelectionKey 的同時最好將 preserveObjectStacking 設(shè)置成 true 。
所以最終的代碼如下所示:
<canvas id="canvasBox" width="600" height="600"></canvas>
<script src="../../script/fabric.js"></script>
<script>
window.onload = function() {
// 使用 元素id 創(chuàng)建畫布,此時可以在畫布上框選
const canvas = new fabric.Canvas('canvasBox', {
width: 400,
height: 400,
// 元素對象被選中時保持在當(dāng)前z軸,不會跳到最頂層
preserveObjectStacking: true, // 默認(rèn)false
altSelectionKey: 'altKey', // 選中元素后,按住alt鍵,選擇被遮擋的部分也能移動當(dāng)前選中的元素
})
// 圓形
circle = new fabric.Circle({
name: 'circle',
top: 60,
left: 60,
radius: 60, // 圓的半徑 60
fill: 'yellowgreen'
})
// 矩形
rect = new fabric.Rect({
name: 'rect',
top: 30, // 距離容器頂部 60px
left: 100, // 距離容器左側(cè) 200px
fill: 'orange', // 填充a 橙色
width: 100, // 寬度 100px
height: 100 // 高度 100px
})
// 將矩形添加到畫布中
canvas.add(circle, rect)
}
</script>
官方文檔的描述對于剛接觸 Fabric.js 的工友來說可能會有點懵。學(xué) Canvas 相關(guān)技術(shù)建議動手實踐一下~
代碼倉庫
? Fabric.js 元素選中時保持原來層級(按著alt可繼續(xù)選中)
推薦閱讀
??《Fabric.js 動態(tài)設(shè)置字號大小》
??《Fabric.js 上劃線、中劃線(刪除線)、下劃線》
??《Fabric.js 橡皮擦的用法(包含恢復(fù)功能)》
點贊 + 關(guān)注 + 收藏 = 學(xué)會了
代碼倉庫