Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete javascript canvas

I want to have a bunch of objects, let's say:

function Block() {
  this.canvas;
}

blocks = [];

And I will at occasions specify:

block[x] = new Block();

and then:

block.canvas = document.createElement('canvas');

But I will also want to delete this new canvas to free up memory sometimes. Do I just need to do:

block.canvas = null; (or whatever the appropriate method is)

And then javascript will free up the memory at some stage? Or is there an explicit way to delete the object and free up the memory?

Thanks!

like image 678
saward Avatar asked Aug 14 '12 09:08

saward


People also ask

How do you clear canvas in react?

Use: context. clearRect(0, 0, canvas. width, canvas. height);

What is JavaScript canvas used for?

<canvas> is an HTML element which can be used to draw graphics via scripting (usually JavaScript). This can, for instance, be used to draw graphs, combine photos, or create simple animations.


1 Answers

Memory, that is taken by objects, that are referenced nowhere, is recovered in JavaScript by the garbage collection (MDN docu on this).

So in order to free up the memory, you just have to delete all references to your canvas objects and in the next run of the garbage collector, the memory will be freed again.

This can be done, like you did, using block.canvas = null; or (depending on the objects/properties scope) by delete block.canvas.

But be sure, that you remove every reference. This can also be references by the DOM or any other object!

like image 126
Sirko Avatar answered Sep 20 '22 13:09

Sirko