赞
踩
在fabric使用过程中,如果想要玩各种花样,那么fabric的事件监听是一定、必须、肯定要掌握!!!
例子就用vue项目组件里的代码,fabric的使用跟vue、react、angular之类的框架都没任何关系!
并且本demo只对功能进行讲述,实际项目使用肯定要进行封装,别直接就照抄导致写的丑!
代码中监听事件回调函数里的第一个参数,根据事件的不同,有目标图形信息、坐标信息等,自己一看就看得懂了,不讲解;
代码只简单介绍一些常用的目标监听事件,更全面的、更多花样的玩法自行查阅官网即可~~
- <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>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。