Search code examples
javascriptangularfabricjs

LoadFromJson not working/Ignoring the Object Properties after Uploading with fabric text


These are the steps I follow, during the uploading and downloading of the canvas. This project is doing in angular.

  1. I save canvas to DB/text files using: JSON.stringify (Working well with Serialization)
  2. I load canvas from that TextFile for editing: loadFromJSON (Uploads Correctly)
  3. Making some changes in the uploaded canvas and uploading again the text, Itext extended classes are truncated.

image

Supporting code is given below.

/// 
/// SAVING TO TEXT FILE FORMAT
///
async onSave(layoutName:any) {
    this.layoutName =layoutName;      
    console.log(JSON.stringify(this.canvasJson));  
    if(this.canvasJson) {
      let blob = new Blob([JSON.stringify(this.canvasJson)], { type: 'text/plain' });
      FileSaver.saveAs(blob, this.layoutName + '.text'); 
      this.layoutName = null; 
    }   
    this.fabricService.addGrid(this.fabricService.canvas);
    this.addNameModel.hide();
  }

///
/// TEXT FILE TO CANVAS
///
async onChange(event:any): Promise<void> {
  const files = event.target.files;
  let file = files[0];  
  if(file) {
    const data = await new Response(file).text(); // .json()   
    console.log(data);
    this.fabricService.addGrid(this.fabricService.canvas); 
    this.fabricService.canvas.loadFromJSON(data, 
                                            this.fabricService.canvas.renderAll.bind(this.fabricService.canvas));     
    this.fabricService.updateModifications(true);
  }  
  console.log(this.fabricService.canvas);
  this.reset();
  this.uploadPromptModal.hide();
   
  }

What I'm missing?

NB: I think there may be an issue during JSON.stringify(this.canvasJson), which truncates the extended classes.


Solution

  • You should convert your canvas into JSON using this code :

    this.fabricService.canvas.toJSON(["extended_property_1", "extended_property_2" ...])
    

    canvas.toJSON is inbuild function of fabric JS that allow us to serialize canvas into JSON with extended properties(our custom properties).

    More info about canvas.toJSON( )