关于前端:Fabricjs-元素被遮挡的部分也可以操作

8次阅读

共计 1969 个字符,预计需要花费 5 分钟才能阅读完成。

本文简介

点赞 + 关注 + 珍藏 = 学会了

题目:

当两个元素有局部重叠时,选中底层元素后,想通过被盖住的局部挪动元素,该如何实现?

其实 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

所以最终的代码如下所示:

<canvas id="canvasBox" width="600" height="600"></canvas>

<script src="../../script/fabric.js"></script>
<script>
  window.onload = function() {
    // 应用 元素 id 创立画布,此时能够在画布上框选
    const canvas = new fabric.Canvas('canvasBox', {
      width: 400,
      height: 400,
      // 元素对象被选中时放弃在以后 z 轴,不会跳到最顶层
      preserveObjectStacking: true, // 默认 false
      altSelectionKey: 'altKey', // 选中元素后,按住 alt 键,抉择被遮挡的局部也能挪动以后选中的元素
    })

    // 圆形
    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, // 间隔容器左侧 200px
      fill: 'orange', // 填充 a 橙色
      width: 100, // 宽度 100px
      height: 100 // 高度 100px
    })

    // 将矩形增加到画布中
    canvas.add(circle, rect)
  }
</script>

官网文档的形容对于刚接触 Fabric.js 的工友来说可能会有点懵。学 Canvas 相干技术倡议入手实际一下~

代码仓库

⭐ Fabric.js 元素选中时放弃原来层级(按着 alt 可持续选中)

举荐浏览

👍《Fabric.js 从入门到收缩👍👍👍》

👍《Fabric.js 动静设置字号大小》

👍《Fabric.js 上划线、中划线(删除线)、下划线》

👍《Fabric.js 自在绘制圆形》

👍《Fabric.js 橡皮擦的用法(蕴含复原性能)》

👍《Fabric.js 缩放画布》

👍《Fabric.js 变换视窗》

👍《Fabric.js 拖拽平移画布》

点赞 + 关注 + 珍藏 = 学会了
代码仓库

正文完
 0