2016-03-08 95 views
0

我使用WebGL和一些用戶,我不能得到WebGL上下文,而一切都表明我應該(最新的Chrome版本等)。我最好的猜測,到目前爲止,是一些分機呼叫getContext('2d')之前,我打電話getContext('webgl'),這將使我的電話回nullsee 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模塊...(僅供參考,上下文thiswindow。我不知道是否預計要麼)

仍然直接調用_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方法。

+1

這個作品https://github.com/ benvanik/WebGL-Inspector/blob/master/core/embed.js – gman

+0

謝謝,通過改變'(type,options)=> {'to'function(type,options){'這非常奇怪,我會檢查 – Guig

+0

感謝張貼這個,這幫助我隔離問題 – Guig

回答

0

事實證明,用function(type, options) {代替(type, options) => {解決了這個問題。我會更深入地看到這個令人驚訝的東西來自哪裏(這是一個Babel錯誤?它是我的環境嗎?有什麼我失蹤與ES2015?等)