Is it possible, given a canvas, to either:
2d or webgl context without calling getContext?getContext, determine whether the returned context was freshly created or preexisting?There isn't any public documented method to detect what context has been requested from the canvas element. The element itself is just the final bitmap and unaware of how the pixels got into it.
The only way that I am aware of is to hack the getContext() call to record what context was requested (or just make a plain wrapper function you call instead of the native call):
// store old call
HTMLCanvasElement.prototype._getContext = HTMLCanvasElement.prototype.getContext;
// store type if requested
HTMLCanvasElement.prototype._contextType = null;
// wrapper for old call allowing to register type
HTMLCanvasElement.prototype.getContext = function(type) {
this._contextType = type;
return this._getContext(type);
};
// check if has context
HTMLCanvasElement.prototype.hasContext = function() {
return this._contextType;
};
//----------------------------------------------------------
//TEST:
var canvas = document.getElementById('canvas'),
ctx;
out.innerHTML += canvas.hasContext() + '<br>';
//-> null
ctx = canvas.getContext('2d');
out.innerHTML += canvas.hasContext();
//-> 2d
<output id=out></output>
<canvas id=canvas width=1 height=1></canvas>
You can now check if there is a context before trying to get a new one:
if (!canvas.hasContext()) ctx = canvas.getContext('webgl');
or to get the same context as before if requested, or new if not:
var ctx = canvas.getContext(canvas.hasContext() || 'webgl');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With