React - Fabric Js getActiveObject not working

1.4k Views Asked by At

I'm new to React with Fabric Js. I just tried to set current active image. My problem is after selecting setting getActiveObject() the canvas image is gone to white color. I tried with some methods, but I can't find the solution.

Demo Link: https://o8n8h.csb.app/ Codesandbix Link: https://codesandbox.io/s/eloquent-platform-o8n8h?file=/src/App.js

Here is my sample code

import React, { Component } from "react";
import { fabric } from "fabric";
export default class App extends Component {
  componentDidMount() {
    this.clg();
  }
  clg = () => {
    var canvas = new fabric.Canvas("a");
    canvas.add(
      new fabric.Rect({
        left: 50,
        top: 50,
        height: 50,
        width: 50,
        fill: "red"
      })
    );
    canvas.add(
      new fabric.Rect({
        left: 70,
        top: 70,
        height: 50,
        width: 50,
        fill: "green"
      })
    );
    canvas.add(
      new fabric.Rect({
        left: 90,
        top: 90,
        height: 50,
        width: 50,
        fill: "blue"
      })
    );
    canvas.renderAll();
  };
  bringToFront = () => {
    var canvas = new fabric.Canvas("a");
    var activeObj = canvas.getActiveObject();
    activeObj &&
      canvas
        .bringToFront(activeObj)
        .discardActiveObject(activeObj)
        .renderAll();
  };
  render() {
    return (
      <div>
        <canvas id="a" width="200" height="200" />
        <button onClick={this.bringToFront}>Bring to front</button>
      </div>
    );
  }
}
1

There are 1 best solutions below

0
On

Initially you have to initiate the fabric object with option {preserveObjectStacking: true} so that the stacking of assets are preserved. e.g.,

clg = () => { var canvas = new fabric.Canvas("a", { preserveObjectStacking:true }); ...

In the bringToFront click handler function you are getting new fabric object instead of using the old fabric object. What you can do is to save the fabric object in state inside this.clg function at the end

this.setState({ canvas })

and have that canvas/fabric object retrieved in bringToFront as

var {canvas } = this.state

This should do the trick. Link to updated codesandbox Working example