The basic answer is that all variables referencing the canvas need to be set to undefined so that the garbage collector can do its job. But sometimes it's not so simple in practice.
Here are several tricky situations I came across when trying to completely remove dynamically-created HTML canvas elements to avoid memory leaks:
(1) Methods I had added to the canvas element held their own references to it (creating a cycle). I fixed this by deleting all custom properties when removing 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 referenced the canvas. Fixed by setting them all to undefined:
_myVar = myBuilder = myObserver = undefined;
(3) A variable referenced the canvas' context: var ctx = myCanvas.getContext('2d'); This held on to the canvas in some browsers (even after setting myCanvas = undefined). Fixed by clearing that variable too:
ctx = undefined;
myCanvasfrom everywhere setting variables tonull