In Kidz Fun Art, I recently increased the resolution of images by two, letting young artists draw at much higher quality (important for my 10 year old who was hitting the limits of the program, she’s amazing). However this introduced an annoying crash on Safari where, after loading four or five images to edit, it would reload the browser from scratch. Not a great user experience.

The Problem

It turns out that too many Canvas DOM elements were not being cleaned up by the browser, even though they were garbage collected and not in the DOM. The app makes very liberal usage of temporarily created Canvas elements for manipulating pixels, and I had thought that simply letting the garbage collector clean them up, but this is apparently insufficient.

The Fix

There were over 80 places in the code that contained

document.createElement("canvas")

I initially replaced this with a simple function to make it easy to have one place to add debug logs.

function makeSimpleCanvas() {
return document.createElement("canvas");
}

Next, to ensure that every temporary canvas fully releases its memory, I added a new function that sets the height and width to zero. I called this function from many places where the code was simply creating a temporary canvas and it was obvious that the canvas was no longer needed.

function releaseCanvas(canvas: HTMLCanvasElement): void {
// Setting either dimension to 0 releases the pixel buffer in every engine.
canvas.width = 0;
canvas.height = 0;
}

Unfortunately, this didn’t cover all the areas in which canvases were not fully cleaned up. I went through all the places where canvas elements were removed from the DOM and explicitly called releaseCanvas on them too.

The Result

After all that work, Kidz Fun Art now runs nice and reliably at the higher resolution. The great outcome of this is that it likely also fixed a real long term issue that just required many hours of use to occur rather than a few minutes, so, yay!