Out of Memory error in Fabric.js canvas causing blank screen in Chrome in mobile Devices

Description:

I am encountering an issue while using Fabric.js canvas for rendering objects onto the canvas. During the process, the canvas becomes blank, and Chrome throws an “Out of Memory” error.

Here’s a summary of the problem:

1.Context: I’m utilizing Fabric.js to render objects onto the canvas in my web application.

2.Issue: At some point during the canvas rendering process, the canvas goes blank.

3.Error: Chrome displays an “Out of Memory” error.

4.Observations: This issue seems to occur when there are a considerable number of objects or complex shapes being rendered onto the canvas.

5.Attempts: I’ve tried optimizing the code by reducing unnecessary object duplication and using fabric.js methods efficiently, but the problem persists.

Please check below image

Please check

  const canvasConfigOptions2 = {
      hoverCursor: 'default',
      selection: false,
      selectionBorderColor: '#00c3f9',
      selectionColor: 'rgba(0, 195, 249, 0.2)',
      preserveObjectStacking: true,
      originX: 'center',
      originY: 'center',
      fireRightClick: false,
      perPixelTargetFind: false
  }

      let height2 = document.getElementById('canvas-wrapper').offsetHeight;

      let width2 = document.getElementById('canvas-wrapper').offsetWidth;

      const zoomLevelX = this.isFullScreen == true ? width2 / this.zoomWidthRef : (width2 - 40) /      this.zoomWidthRef;

       const zoomLevelY = this.isFullScreen == true ?  height2 / this.zoomHeightRef : (height2 - 60) / this.zoomHeightRef;

       const zoomLevel = Math.min(zoomLevelX, zoomLevelY); // for regenerate the issue you can take zoomlevel above 1;

       this.zoomWidthRef = 3000px;

       this.zoomHeightRef = 3000px;

       this.canvas = new fabric.Canvas('canvas', canvasConfigOptions2);

       this.canvas.setZoom(zoomLevel);

       this.canvas.setDimensions({

        width: Math.round(this.zoomWidthRef * zoomLevel),
        height: Math.round(this.zoomHeightRef * zoomLevel)

        })
      this.canvas.calcOffset();

     // render json on fabric.js canvas

     this.canvas.loadFromJSON(json, async function () {
        this.canvas.renderAll();
     })
---- Add canvas tag into html file:

//html code start

<div class="canvas-wrapper canvas-wrapper2" style="position: absolute;top: 60px;left: 0; display: flex;justify-content: center;" id="canvas-wrapper"> <canvas id="canvas" class="shadow canvas-style" style="cursor: none;"></canvas> </div>

//html code end

image:

Additional context:

Browser: Chrome [Version 120.0.6099.144] , safari All version

Fabric.js version: [1.7.22]

angular version : [6.0.0]

Approximate number of objects being rendered: [10 to 15]

Note: This issue generate mostly in mobile browser

I’d appreciate any insights or suggestions on how to tackle this “Out of Memory” error while rendering on the Fabric.js canvas in Chrome. Thank you!