Both the CanvasRenderingContext2D and WebGLRenderingContext classes have the canvas element associated with them as the property canvas
; and, like normal, both context instances and their canvases will be garbage collected when your code no longer makes references to them at run time.
You can use this function to create a new context
function newContext({width, height}, contextType = '2d') {
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
return canvas.getContext(contextType);
}
const ctx = newContext({width: 100, height: 100});
console.log(ctx.canvas.width == 100) // true
And by making use of dereferencing you can easily create a clone of a DOM canvas for frame buffering like this:
const domCanvas = document.getElementById('myCanvas');
const frameBuffer = newContext(domCanvas);
frameBuffer.drawImage(domCanvas, 0, 0);
Which will create a context with the same width and height as the canvas element passed in. You can extend the function as needed.