Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 377
Ziteng Wang Avatar asked Feb 20 '17 12:02

Ziteng Wang


People also ask

Can I use JavaScript in Vue?

Single-file components and readability Components represent encapsulated elements of your interface. In Vue. js, components can be written in HTML, CSS, and JavaScript without dividing them into separate files.

How add VueJS to HTML?

The simplest way to get started with Vue is to grab the development version script for it and add it to the head tag of your HTML file. Then you can start Vue code inside the HTML file inside of script tags. And have the Vue code connect up with an existing element on your HTML page.


2 Answers

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.

like image 153
laverick Avatar answered Sep 21 '22 14:09

laverick


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>
like image 35
Ben Winding Avatar answered Sep 21 '22 14:09

Ben Winding