Javascript 覆盖html5画布getContext

Javascript 覆盖html5画布getContext,javascript,html5-canvas,webgl,prototype,overwrite,Javascript,Html5 Canvas,Webgl,Prototype,Overwrite,我使用的是WebGL,对于一些用户来说,我无法获得WebGL上下文,而一切都表明我应该这样做(最新的Chrome版本等)。到目前为止,我最好的猜测是,在我调用getContext('2d')之前,一些扩展调用getContext('webgl'),这将使我的调用返回null() 因此,我试图覆盖getContext,以防止调用“2d”上下文: const _getContext = HTMLCanvasElement.prototype.getContext; HTMLCanvasElement

我使用的是
WebGL
,对于一些用户来说,我无法获得
WebGL
上下文,而一切都表明我应该这样做(最新的Chrome版本等)。到目前为止,我最好的猜测是,在我调用
getContext('2d')
之前,一些扩展调用
getContext('webgl')
,这将使我的调用返回
null
()

因此,我试图覆盖
getContext
,以防止调用“2d”上下文:

const _getContext = HTMLCanvasElement.prototype.getContext;
HTMLCanvasElement.prototype.getContext = (type, options) => {
  console.log(this, arguments);

  if (type !== 'webgl' && type !== 'experimental-webgl') {
    setTimeout(() => {
      throw new Error('getContext asked for type '+type+' and options '+options);
    }, 0);
    return null;
  }

  let res, error;
  try{
    // res = _getContext.apply(this, [type, options]);
    res = _getContext.apply(this, arguments);
  } catch (e) {
    console.log('oups!', e);
    error = e;
    // this will be TypeError: Illegal invocation(…)
  }

  if (error)
    throw error;
  return res;
};
这不起作用:当调用
canvas.getContext(“webGL”)
时,抛出错误
TypeError:invalign调用(…)
canvas
是一个canvas DOM元素),更令人惊讶的是,
参数
[type,options]
不同,但更像

// result from console.log(arguments);
0: require(id)
1: Object
2: Module
3: "/client/modules/video-player/VideoPlayer.jsx"
4: "/client/modules/video-player"
callee: (require,exports)
length: 5
我不确定这是否是因为我正在使用ES2015模块。。。(仅供参考,此的上下文是
窗口
。我也不知道这是否符合预期)

仍然直接调用
\u getContext.apply(此[type,options])
而不是
\u getContext.apply(此,参数)
不会删除错误

最后,直接在DOM元素方法上工作很好:

const _getContext = canvas.getContext.bind(canvas);
canvas.getContext = (type, options) => {
  if (type !== 'webgl' && type !== 'experimental-webgl') {
    setTimeout(() => {
      throw new Error('getContext ask for type '+type+' and options '+options);
    }, 0);
    return null;
  }
  return _getContext(type, options);
};

但是我宁愿覆盖原型,以确保可疑调用不会在DOM元素实例化和我覆盖其
getContext
方法之间被调用。

结果是将
(type,options)=>{
替换为
函数(type,options){
修复了这个问题。我将进一步研究这个令人惊讶的事情是从何而来的(这是一个
Babel
bug吗?是我的环境吗?ES2015有什么我遗漏的吗?等等)

这很有效谢谢,通过将
(类型,选项)=>{
更改为
函数(类型,选项)来修复这个问题{
这非常奇怪,我要感谢你发布这篇文章,这篇文章帮助我解决了这个问题。
=>
的问题在于它只是
绑定的一个快捷方式,这意味着它绑定了创建函数时这个
的任何内容。在你的例子中,你需要在函数I调用。您不能使用
=>
bind
执行此操作。请查看底部附近的箭头函数。