1、Fabric.js 入门(vue3 + vite + ts)

本文展示了如何在Vue项目中安装和使用Fabric.js库来创建canvas元素,并实现自适应屏幕尺寸和设置背景。同时,提到了通过typescript编写的组件如何初始化canvas,以及在窗口resize时调整canvas大小和渲染。还提及了添加矩形对象到canvas上的示例。
摘要由CSDN通过智能技术生成

安装Fabric.js依赖

npm i fabric --save

在这里插入图片描述
在这里插入图片描述
我项目中使用的是这个版本…

创建Canvas容器

<template>
  <div style="padding: 20px">
    <canvas
      width="500"
      height="500"
      id="canvas"
      style="border: 1px solid rgba(69, 154, 235, 0.55)"
    ></canvas>
  </div>
</template>
<script lang="ts">
  import { defineComponent, onMounted } from 'vue';
  import { fabric } from 'fabric';

  export default defineComponent({
    components: {},
    setup() {
      let canvasContainer = null;

      onMounted(() => {
        initCanvas();
      });

      async function initCanvas() {
        let canvas = new fabric.Canvas('canvas'); // 实例化fabric,并绑定到canvas元素上
        canvasContainer = canvas;
      }

      return {};
    },
  });
</script>

canvas 可视化区域自适应滚动&设置背景

<template>
  <div class="hmi">
    <div class="hmi__content">
      <div class="hmi__content_content" ref="wrapElRef">
        <ScrollContainer>
          <canvas width="1920" height="1080" id="canvas"></canvas>
        </ScrollContainer>
      </div>
    </div>
  </div>
</template>
<script lang="ts">
  import { defineComponent, onMounted, ref, unref, nextTick, onUnmounted } from 'vue';
  import { useEventListener } from '/@/hooks/event/useEventListener';
  import { fabric } from 'fabric';
  import { ScrollContainer } from '/@/components/Container';
  import hmi_bg from '/@/assets/fabric/hmi_bg.svg';

  export default defineComponent({
    components: {
      ScrollContainer,
    },
    setup() {
      let canvasContainer = null;
      const wrapElRef = ref<HTMLDivElement | null>(null);
      let removeResizeFn: Fn = () => {};

      const onResize = () => {
        const contentEl = unref(wrapElRef);
        if (!contentEl) return;
        const clientHeight = contentEl.clientHeight;
        const clientWidth = contentEl.clientWidth;
        const defaultWidth = canvasContainer?.width || 1920;
        const defaultHeight = canvasContainer?.height || 1080;
        canvasContainer.setHeight(clientHeight < defaultHeight ? defaultHeight : clientHeight);
        canvasContainer.setWidth(clientWidth < defaultWidth ? defaultWidth : clientWidth);
        canvasContainer.renderAll(); //重新渲染
      };

      onMounted(() => {
        initCanvas();
      });

      onUnmounted(() => {
        removeResizeFn();
        handleDispose();
      });

      async function initCanvas() {
        let canvas = new fabric.Canvas('canvas'); // 实例化fabric,并绑定到canvas元素上
        nextTick(() => {
          const { removeEvent } = useEventListener({
            el: window,
            name: 'resize',
            listener: onResize,
            wait: 100,
          });
          removeResizeFn = removeEvent;
        });
        const contentEl = unref(wrapElRef);
        const clientHeight = contentEl?.clientHeight;
        const clientWidth = contentEl?.clientWidth;
        if (clientHeight > 200) {
          const val = clientHeight / 1080;
          canvas.setZoom(val);
        }
        canvas.setHeight(clientHeight < 1080 ? 1080 : clientHeight);
        canvas.setWidth(clientWidth < 1920 ? 1920 : clientWidth);
        // 设置背景
        canvas.setBackgroundColor(
          {
            source: hmi_bg,
            repeat: 'repeat',
          },
          canvas.renderAll.bind(canvas)
        );
        canvasContainer = canvas;
      }

      /**
       * 清空画布
       */
      function handleDispose() {
        canvasContainer && canvasContainer.dispose(); // 清除一个画布元素并删除所有事件侦听器
      }

      return {
        wrapElRef,
      };
    },
  });
</script>
<style lang="less">
  .hmi {
    &__content {
      width: calc(100% - 40px);
      margin: 20px;
      border: 1px solid rgba(112, 112, 112, 0.2);
      box-shadow: 0 1px 6px rgb(0 0 0 / 10%) !important;
      border-radius: 20px;
      height: calc(100vh - 110px - 60px - 40px);
      position: relative;
      overflow: auto;
      background-color: #00061c;

      &_content {
        position: absolute;
        width: calc(100%);
        height: calc(100%);
        overflow: auto;
      }
    }
  }
</style>

此处背景引用的是外部svg,这里只介绍了宽高设置和背景设置,更多配置可去 官方文档查看
在这里插入图片描述
在这里插入图片描述

添加一个矩形框

function addRect() {
  const rect = new fabric.Rect({
    top: 100, // 距离容器顶部 100px
    left: 100, // 距离容器左侧 100px
    fill: 'orange', // 填充 橙色
    width: 100, // 宽度 100px
    height: 100, // 高度 100px
  });
  
  // 将矩形添加到画布中
  canvasContainer.add(rect);
}

在这里插入图片描述

这只是简单的创建一个页面,更多配置尽请期待…

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值