Ziteng Wang
Ziteng Wang

Reputation: 233

How can I set up Fabric.js in vue?

I just came across the same combination: Fabric.js and Vue.js and was wondering, but I'm working with VueJs few days and I don't know how to set up fabric in vue.
Can you share some experience for me?

Upvotes: 23

Views: 19499

Answers (5)

holy-jesus
holy-jesus

Reputation: 1

Composition API version of the code provided by @ben-winding.

<template>
    <canvas ref="can" width="200" height="200"></canvas>
</template>

<script setup>
import { useTemplateRef, onMounted } from "vue";
import { fabric } from "fabric";

const can = useTemplateRef("can")

onMounted(() => {
    const canvas = new fabric.Canvas(can.value)
    const rect = new fabric.Rect({
        fill: 'red',
        width: 20,
        height: 20
    });
    canvas.add(rect);
})
</script>

Upvotes: 0

James Marx
James Marx

Reputation: 1

Fabric doesn't export fabric directly.

Try importing Canvas.

import { Canvas } from "fabric"

Upvotes: 0

Ben Winding
Ben Winding

Reputation: 11787

Install Fabric

yarn add fabric # or npm install -s fabric

Basic component (based on @laverick's answer):

<template>
  <canvas ref="can" width="200" height="200"></canvas>
</template>

<script>
import { fabric } from 'fabric';

export default {
  mounted() {
    const ref = this.$refs.can;
    const canvas = new fabric.Canvas(ref);
    const rect = new fabric.Rect({
      fill: 'red',
      width: 20,
      height: 20
    });
    canvas.add(rect);
  }
};
</script>

Upvotes: 23

laverick
laverick

Reputation: 734

Assuming you're using ES6 and a bundler such as Webpack you can start using Fabric.js as follows:

At the command line

npm install fabric

or

yarn add fabric

Then import it in your .js file.

import { fabric } from 'fabric'

Then set up your Canvas in Vue's mounted: method.

Note: For me the default fabric npm module resulted in quite a large package. I ended up using the fabric-browseronly module instead. Fabric.js has a lot of features you might not need, in which case you could build your own version here or via the command line.

Upvotes: 20

Fabol Lous
Fabol Lous

Reputation: 34

Fabric follows a pretty traditional distribution layout.

You want to use files from the dist directory. fabric.js for development work and fabric.min.js for the live site.

Upvotes: 0

Related Questions