【Fabric.js】监听画布or元素的点击、选中、移动、添加、删除销毁、变形等各事件

在fabric使用过程中,如果想要玩各种花样,那么fabric的事件监听是一定、必须、肯定要掌握!!!

例子就用vue项目组件里的代码,fabric的使用跟vue、react、angular之类的框架都没任何关系!

并且本demo只对功能进行讲述,实际项目使用肯定要进行封装,别直接就照抄导致写的丑!

代码中监听事件回调函数里的第一个参数,根据事件的不同,有目标图形信息、坐标信息等,自己一看就看得懂了,不讲解;

代码只简单介绍一些常用的目标监听事件,更全面的、更多花样的玩法自行查阅官网即可~~

html 复制代码
<template>
  <div class="cdie">
    <canvas id="c" ref="canvas"></canvas>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import { fabric } from "fabric";
let canvas = null;
onMounted(() => {
  canvas = new fabric.Canvas("c", {
    backgroundColor: "grey",
    minZoom: 1,
    maxZoom: 1.5,
    width: 1000,
    height: 444,
  });
  canvas
    .on('selection:cleared', (e) => {
      // 画布内取消选中后的事件
      console.log(canvas.getActiveObject());
    })
    .on('selection:created', (e) => {
      // 初次选中图形目标的事件
      console.log(canvas.getActiveObject());
    })
    .on('selection:updated', (e) => {
      // 变更选中图形目标的事件
      console.log(canvas.getActiveObject());
    })
    .on('mouse:down', (e) => {
      // 画布鼠标按下事件
      console.log(e);
    })
    .on('mouse:up', (e) => {
      // 画布鼠标松开事件
      console.log(e);
    })
    .on('mouse:move', (e) => {
      // 画布鼠标移动事件
      console.log(e);
    })
    .on('object:added', (e) => {
      // 当有图形添加进画布时触发的事件
      console.log(e.target);
    })
    .on('object:removed', (e) => {
      // 当有图形从画布销毁时触发的事件
      console.log(e.target);
    })
    .on('object:moving', (e) => {
      // 图形移动时触发;
      console.log(e.target);
    })
    .on('object:scaling', (e) => {
      // 图形缩放时触发;
      console.log(e.target);
    })
  window.fabric = canvas
  var line = new fabric.Line([10, 10, 333, 200], {
    strokeWidth: 1,
    stroke: "yellow",
    id: "linexx",
  });
  var rect = new fabric.Rect({
    left: 100,
    top: 100,
    width: 100,
    height: 50,
    fill: "pink",
  });
  var rect2 = new fabric.Rect({
    left: 400,
    top: 100,
    width: 100,
    height: 50,
    fill: "yellow",
  });

  canvas.add(line);
  canvas.add(rect);
  canvas.add(rect2);
  canvas.renderAll()
});
</script>
<style>
img {
  margin: 10px !important;
}
</style>
<style scoped lang="less">
.bss {
  margin: 10px;
  object-fit: contain;
  width: 22px;
  height: 22px;
  border: 1px solid rgb(46, 46, 46);
}

.cdie {
  width: 100%;
  text-align: center;
  display: flex;
}
</style>
相关推荐
yz-俞祥胜3 分钟前
【疑难杂症】Vue前端下载文件无法打开 已解决
前端·javascript·vue.js
TE-茶叶蛋7 分钟前
前端错误监听与上报框架工作原理,如:Sentry
前端·javascript·sentry
漫谈网络13 分钟前
TypeScript 和 JavaScript核心关系及区别
前端·javascript·typescript
aiweker22 分钟前
python web 开发-Flask-Login使用详解
前端·python·flask
m0_679927201 小时前
练习小项目7:天气状态切换器
前端·javascript·css·html
OK_boom1 小时前
React-改变当前页class默认的样式
前端·javascript·react.js
哎呦你好1 小时前
【background】CSS 背景全解析:从基础属性到视觉魔法
前端·css·人工智能·python
yuanyxh2 小时前
commonmark.js 源码阅读(二) - Inline Parser
前端·javascript·html
韩明君2 小时前
前端学习笔记——Promis.All
前端·笔记·学习
斯~内克2 小时前
Vite + Vue 工程中,为什么需要关注 `postcss.config.ts`?
前端·vue.js·postcss