我使用WebGL
和一些用戶,我不能得到WebGL
上下文,而一切都表明我應該(最新的Chrome版本等)。我最好的猜測,到目前爲止,是一些分機呼叫getContext('2d')
之前,我打電話getContext('webgl')
,這將使我的電話回null
(see here)覆蓋HTML5畫布getContext
所以我試圖覆蓋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: Illegal invocation(…)
被拋出時(canvas
是一個Canvas DOM元素)更令人驚訝的,arguments
不像[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模塊...(僅供參考,上下文this
是window
。我不知道是否預計要麼)
仍然直接調用_getContext.apply(this, [type, options])
而不是_getContext.apply(this, arguments)
不會刪除該錯誤。
最後直接在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
方法。
這個作品https://github.com/ benvanik/WebGL-Inspector/blob/master/core/embed.js – gman
謝謝,通過改變'(type,options)=> {'to'function(type,options){'這非常奇怪,我會檢查 – Guig
感謝張貼這個,這幫助我隔離問題 – Guig