theme: smartblue
我报名参加金石计划1期挑战——瓜分10万奖池,这是我的第13篇文章,点击查看活动详情
本文简介
点赞 + 关注 + 收藏 = 学会了
题目:
当两个元素有部分重叠时,选中底层元素后,想通过被盖住的部分移动元素,该如何实现?
其实 Fabric.js
已经提供了相应的 API
去完成上面的需求了。但直到今天, Fabric.js
官方文档还是那么晦涩难懂,于是就有了本文。
动手实现
先来看看默认的效果
默认情况下,被选中的元素会跑到视图的最顶层,释放后会恢复到原来的层级。
如果需要做到“本文简介”提到的效果,需要将 preserveObjectStacking
设置为 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
设置为 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
null
or 'none' or any other string that is not a modifier key feature is disabled.
altSelectionKey
可以设置选中的组合键,可传入 'altKey'、 'shiftKey'、 'ctrlKey'
三个值。分别对应键盘上的 alt键
、shift键
、ctrl键
。
如果传入的是 'null'
、'none'
或其他不相关的字符,就不采用任何功能键配合(当没事发生过)。
由于 Fabric.js
的默认操作逻辑(前面演示过),在设置 altSelectionKey
的同时最好将 preserveObjectStacking
设置成 true
。
所以最终的代码如下所示:
```html
```
官方文档的描述对于刚接触 Fabric.js
的工友来说可能会有点懵。学 Canvas
相关技术建议动手实践一下~
代码仓库
⭐ Fabric.js 元素选中时保持原来层级(按着alt可继续选中)
推荐阅读
点赞 + 关注 + 收藏 = 学会了