检测canvas是否已有上下文

时间:2014-11-17 19:57:30

标签: html5 canvas webgl

在给定canvas的情况下,是否可以:

  • 检测是否已有关联的2dwebgl上下文而未调用getContext
  • 或者在调用getContext时,确定返回的上下文是刚刚创建还是已存在?

1 个答案:

答案 0 :(得分:3)

没有任何公开记录的方法来检测canvas元素请求的上下文。元素本身只是最终的位图,并且不知道像素是如何进入的。

我所知道的唯一方法是破解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
&#13;
<output id=out></output>
<canvas id=canvas width=1 height=1></canvas>
&#13;
&#13;
&#13;

现在,您可以在尝试获取新内容之前检查是否有上下文:

if (!canvas.hasContext()) ctx = canvas.getContext('webgl');

或者如果需要,可以获得与之前相同的上下文,如果不是,则获取新的上下文:

var ctx = canvas.getContext(canvas.hasContext() || 'webgl');