Search code examples
javascriptcanvasfabricjs

Not able to set Uniform stroke width on canvas.loadFromJSON?


So I have specified the Rect like:

addRect() {
    let square = new fabric.Rect({
      width: 20,
      height: 30,
      stroke:"yellow",
      strokeWidth:10,
      left: 50,
      top: 50,
      strokeUniform:true,
      fill:"rgba(0,0,0,0.2)",
      flipX:true
    });
    this.canvas.add(square);
  }

On canvas I am getting something like this: The stroke width for the square is accurate

I temporarily save the canvas Data:

saveData() {
    let jsonData = JSON.stringify(this.canvas);
    localStorage.setItem('data', jsonData);
    this.dataPreview.nativeElement.value = jsonData;
  }

And then I am loading this data back on canvas:

loadData() {
    let jsonData = localStorage.getItem('data');
    this.canvas.loadFromJSON(
      jsonData,
      () => {
        this.canvas.requestRenderAll();
        this.dataPreview.nativeElement.value = jsonData;
      },
      this.onDataLoadFailed
    );
  }

I get something like this on canvas: enter image description here

How should I fix this ? I think that the problem might be because the JSON data doesn't have any value for strokeUniform.


Solution

  • strokeUniform property have been commented from toObject.

    A workaround is to include the property as argument of the toJSON method

    console.log(JSON.stringify(canvas.toJSON("strokeUniform")));