Nawaraj
Nawaraj

Reputation: 425

How to make Fabric js reactive using Vue js?

I am new in Vue js. So I am trying to do some practice using Fabric js and Vue js. I try to make my canvas reactive by using Vus js but nothing happens. By default in canvas, it displays "Text". Then after a button is clicked that text most change into "Test bus". But text in a canva is not change.

main.js

import Vue from 'vue'
import App from './App.vue'
import { fabric } from 'fabric'
import { eventBus } from './bus';

var vm = new Vue({
  el: '#app',
  data: {
    showText: 'Test'
  },
  render: h => h(App),
  mounted() {
    var canvas = new fabric.Canvas('canvas', {
      width: 500,
      height: 500
    });
    eventBus.$on('grabData', (gg) => {
      this.showText = gg;
    });
    var addtext = new fabric.Textbox(this.showText, {
      left: 200,
      top: 200,
      fill: "#A7A9AC",
      strokeWidth: 2,
      fontFamily: 'Arial'
        });
      canvas.add(addtext);
      canvas.renderAll();
  }
});

bus.js

import Vue from 'vue';
export const eventBus = new Vue();

App.vue

<template>
  <div id="app">
    <canvas id="canvas" :style="myStyle"></canvas>
    <button @click="changeName()">Change</button>
  </div>
</template>

<script>
import { eventBus } from './bus';

export default {
  name: 'app',
  data () {
    return {
    }
  },
  methods: {
    changeName() {
      eventBus.$emit('grabData', "Test bus");
    }
  },
  computed: {
    myStyle() {
      return {
        border: '1px solid black'
      }

    }
  }
}
</script>

Main.js contain a default text(Test) on showText variable. Its value is changed to the event bus through App.vue. And App.vue contain a button which helps to change the value of showText. When I click the button then Value only change in a showText variable but in a canvas.

Upvotes: 1

Views: 2143

Answers (1)

Durga
Durga

Reputation: 15604

eventBus.$on('grabData', (gg) => {
  addtext.set('text',gg);
});

You need to set value to text object using set('text',textValue) ,it will update on next render call.

Upvotes: 1

Related Questions