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

拥有回忆 提交于 2019-12-03 13:49:23

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/19030174/how-to-manage-memory-in-case-of-multiple-fabric-js-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!