Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manage memory in case of multiple fabric js canvas?

In my application, I have multiple Fabric.js canvases, There is no limit on the number of canvases. I'll render heavy JSON via loadFromJson method of Fabric.js.

So I want to release the fabric object memory if the canvas is not in use. How can I do that?

At a time only one canvas will be visible. But I have to render all the canvases as the page loads. Canvas is actually a page and user can switch between pages via clicking on page number or something else.

Remember user can come back to any canvas any time and try to doodle or use any other Fabric.js functionality.

Here is my HTML structure:

<style>
 .fabricCanvas {
   border: 1px solid green;
   margin: 5px;
 }

 .canvas-container {
    margin: 5px;    
 }
</style>
<canvas class="fabricCanvas" width="300" height="300"></canvas>
<canvas class="fabricCanvas" width="300" height="300"></canvas>
<canvas class="fabricCanvas" width="300" height="300"></canvas>
<canvas class="fabricCanvas" width="300" height="300"></canvas>

My JS code to store fabric instances

var canvasInstances = [];
$('canvas.fabricCanvas').each(function () {
  var fabricCanvasObj = new fabric.Canvas(this, {
  isDrawingMode: true
});
  canvasInstances.push(fabricCanvasObj);
  fabricCanvasObj.renderAll();
});
console.log(canvasInstances[0]);

I am storing instances so that I can use them later. I want this for better memory management, basically loading and unloading instances as and when needed.

Sample situation DEMO is here. In this demo consider that the canvases are over each other using z-indexes but they are the part of DOM and has already been rendered on page load.

Let me know in case of any doubt, I can explain further.

When ever there are more than 5 canvases iPad browser crashes which I think is the memory issue.

like image 518
ʞɹᴉʞ ǝʌɐp Avatar asked Sep 26 '13 13:09

ʞɹᴉʞ ǝʌɐp


1 Answers

You might be interested in 3 things (in the order of significance/destruction):

  1. canvas.clear() — removes all canvas objects from it.

  2. canvas.dispose() — removes all canvas objects AND removes all event listeners

  3. $(canvas.wrapperEl).remove() (using jQuery for illustrative purposes) — to remove canvas wrapper element (which contains upper and lower canvases used by Fabric). This can be done AFTER you call dispose, if the goal is to completely remove Fabric canvas from a document.

like image 94
kangax Avatar answered Nov 14 '22 22:11

kangax