当前位置:   article > 正文

4、Fabric.js 常用的方法&事件_fabric.js 事件

fabric.js 事件

Fabric.js Event demo
下面只是我用到的一些基本事件和方法,当做笔记记录下来…

画布相关

  • getObjects() 获取 canvas 画布的所有对象
  • setActiveObject() 设置 canvas 画布选中元素
  • getActiveObject() 获取 canvas 画布选中元素
  • discardActiveObject() 取消 canvas 画布中所有对象的选中状态
  • selection canvas 画布框选选中:默认为true,设置为false 则不可被选中。可以用于同时选中多个元素对象的情况。
canvas.selection = false; // canvas无法被选中
  • 1

在这里插入图片描述
如果想要禁用多选如何处理?我们可以通过 selection:created 事件进行控制。

  • selection:created 初次选中画布
canvas.on('selection:created', (e) => {
  if (e?.selected && e?.selected.length > 1) {
    canvas.discardActiveObject();
  } else {
    const selectTarget = e?.selected[0];
    canvasContainer.setActiveObject(selectTarget);
  }
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • selection:updated 画布选择变化

  • selection:cleared 清空画布选中

  • mouse:down 鼠标按下

  • mouse:up 鼠标抬起

  • mouse:move 鼠标移动

  • mouse:dblclick 鼠标双击

  • object:added 添加图层

  • object:modified 编辑图层

  • object:removed 移除图层

  • object:moving 对象移动

  • object:added 对象被加入

  • object:removed 对象被移除

对象相关

  • mouseup 鼠标抬起
  • mousedown 鼠标按下
  • mousemove 鼠标移动
  • mouseup:before 鼠标抬起前
  • mousedown:before 鼠标按下前
  • mousemove:before 鼠标移动前
  • mousedblclick 鼠标双击
  • mousewheel 鼠标滚动
  • mouseover 鼠标移入
  • mouseout 鼠标移除

示例

  • mousedown 点击事件
function addRect() {
  const rect = new fabric.Rect({
    top: 100, // 距离容器顶部 100px
    left: 100, // 距离容器左侧 100px
    fill: 'orange', // 填充 橙色
    width: 200, // 宽度 100px
    height: 200, // 高度 100px
  });

  rect.on('mousedown', (e) => {
    console.log('mousedown 单击', e);
    const selectTarget = e.transform.target;
    canvasContainer.setActiveObject(selectTarget);
    let activeObject = canvasContainer.getActiveObject();
    console.log('获取画布当前选中的对象', activeObject);
  });
  // 将矩形添加到画布中
  canvasContainer.add(rect);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/98092
推荐阅读
相关标签
  

闽ICP备14008679号