首页 > 解决方案 > LoadFromJson 不工作/在使用织物文本上传后忽略对象属性

问题描述

这些是我在上传和下载画布期间遵循的步骤。这个项目是有角度的。

  1. 我使用以下方法将画布保存到 DB/文本文件:JSON.stringify(与序列化配合得很好)
  2. 我从该 TextFile 加载画布进行编辑:loadFromJSON(正确上传)
  3. 在上传的画布中进行一些更改并再次上传文本,Itext扩展类被截断。

图片

支持代码如下。

/// 
/// 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();
   
  }

我错过了什么?

注意:我认为在 JSON.stringify(this.canvasJson) 期间可能存在问题,它会截断扩展类。

标签: javascriptangularfabricjs

解决方案


您应该使用以下代码将画布转换为 JSON:

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

canvas.toJSON 是它的内置功能,fabric JS它允许我们将画布序列化为具有扩展属性(我们的自定义属性)的 JSON。

有关 canvas.toJSON( ) 的更多信息


推荐阅读