2D Design : fabricjs with nuxt

Fabric Js is a javascript library that includes a lot of design features. I use it for configurator rendering of top view. Integration in nuxt is quite straight forward using an specific interactive canva component that works with pinia data store

Prerequisite : for this tutorial you need to have an existing nuxt3 project up and running, with Pinia store and a basic form interface to interact with your canva design

Add fabric js to your project

First of all, obviously you need to add fabric library to your package list . This can be done via package.json editing, or using one of your favourite package management tool :

pnpm add fabric

Create canva component

creating a component with nuxt is quite straigtforward : create a vue file in component folder. This can be named canva.vue. The code below is the template of your component, note that I repeat width and height elements many times, because I could not find an efficient way of using component variables efficiently. Always some kind of wrong sizing bug when using variables.

Styling here is for a bottom left fixed canva.

.waveCanva{  position:fixed; bottom:0px; left:0;z-index:1050;
  border:1px solid black;   width:300px; height:300px; background:white}
<canvas   id="waveCanvas" ref="canvas" :width="300" height="300" style="width:300px; height:300px"   ></canvas>

Everytoing happens in the mounted hook, that's where we declare the fabricjs canva and define an event on store value change to get the interactivity going

  mounted()
  {
    this.canvas=new fabric.Canvas('waveCanvas')
    this.drawAll()

    this.waveChoixStore.$subscribe((mutation, state) => { this.drawAll()   })
  }
  

Of course you will have to work out your own design within the drawAll method. note that this method is called for every change of status, so remember to clear the canva before each redraw. Your drawAll method will start this way :

    drawAll()
    {

      var state=this.waveChoixStore
    
      this.canvas.clear();
}
To top