The main answer is that all variables that refer to the canvas must be set to undefined so that the garbage collector can do its job. But sometimes itβs not so simple in practice.
Here are some tricky situations that I encountered while trying to completely remove dynamically created HTML canvas elements in order to avoid memory leaks:
(1) The methods that I added to the canvas element contained their own references to it (creating a loop). I fixed this by deleting all user properties when deleting the canvas:
function deleteAllProperties(obj) { for (var key in obj) { if (obj.hasOwnProperty(key)) { delete obj[key]; } } } deleteAllProperties(myCanvas); myCanvas = undefined;
(2) Internal variables in other objects still refer to the canvas. Fixed by setting them all to undefined :
_myVar = myBuilder = myObserver = undefined;
(3) The variable referred to the canvas context: var ctx = myCanvas.getContext('2d'); This was held on canvas in some browsers (even after setting myCanvas = undefined ). Fixed by clearing this variable too:
ctx = undefined;
source share