• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Fabric.js 元素被遮挡的部分也可以操作

武飞扬头像
德育处主任
帮助44

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

01.gif

其实 Fabric.js 已经提供了相应的 API 去完成上面的需求了。但直到今天, Fabric.js 官方文档还是那么晦涩难懂,于是就有了本文。



动手实现

先来看看默认的效果

02.gif

默认情况下,被选中的元素会跑到视图的最顶层,释放后会恢复到原来的层级。

如果需要做到“本文简介”提到的效果,需要将 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 ,可以让元素被选中时保留在原来的层级

 

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 相关技术建议动手实践一下~

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanfbcik
系列文章
更多 icon
同类精品
更多 icon
继续加载