【发布时间】:2015-01-14 20:20:40
【问题描述】:
给定canvas,是否有可能:
- 不调用
getContext就检测它是否已经有关联的2d或webgl上下文? - 或者在调用
getContext时,判断返回的上下文是新创建的还是已经存在的?
【问题讨论】:
给定canvas,是否有可能:
getContext就检测它是否已经有关联的2d或webgl上下文?getContext时,判断返回的上下文是新创建的还是已经存在的?【问题讨论】:
没有任何公开的记录方法来检测从画布元素请求的上下文。元素本身只是最终的位图,不知道像素是如何进入其中的。
我知道的唯一方法是破解 getContext() 调用以记录请求的上下文(或者只是制作一个您调用的普通包装函数而不是本机调用):
// 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>
您现在可以在尝试获取新上下文之前检查是否存在上下文:
if (!canvas.hasContext()) ctx = canvas.getContext('webgl');
如果有请求,则获取与以前相同的上下文,如果没有,则获取新的:
var ctx = canvas.getContext(canvas.hasContext() || 'webgl');
【讨论】: