如何在纯JavaScript中覆盖本机JS函数(canvas的getContext())? [英] How can I override a native JS function ( canvas's getContext() ) in pure JavaScript?
问题描述
当画布元素调用"getContext('webgl')"时,我想返回"null"值.
I'd like to when canvas element calls 'getContext('webgl')', return 'null' value..
我试图找到WebGLRenderingContext
原型并对其进行更新,但是我找不到它.
I tried to find WebGLRenderingContext
prototype and update it, but i can't find it.
WebGLRenderingContext
和WebGLRenderingContextBase
没有prototype.getContext
.
如何更改它返回"null"值?
How can i change it return to 'null' value?
我已经在下面进行了测试.
I've tested with below..
var test = document.createElement('canvas');`
test.getContext("webgl");`
这将返回WebGLRenderingContext
对象...
请帮助我:)
推荐答案
不确定为什么要这么做,但是假设您确切地知道自己在做什么™,则可以这样做:
Not sure why you want to do this, but assuming you Know Exactly What You're Doing™ you can do it this way:
// store a reference to original vector
HTMLCanvasElement.prototype.__oldGetContext = HTMLCanvasElement.prototype.getContext;
// patch
HTMLCanvasElement.prototype.getContext = function(type, options) {
if (type === "webgl" || type === "experimental-webgl") {
console.log("WebGL suppressed!"); // remove this in production
return null;
}
else return this.__oldGetContext(type, options); // call original vector
}
// test (assuming browser do indeed support *webgl...)
var c = document.createElement("canvas");
var ctx = c.getContext("webgl") || c.getContext("experimental-webgl");
// works with 2D
var c2 = document.createElement("canvas");
var ctx2 = c2.getContext("2d");
console.log("2d?", !!ctx2);
probablySupportsContext()
着陆时,您需要对其进行类似的操作.
You will need to do something similar for probablySupportsContext()
when it lands.
这项工作的关键是在任何其他代码使用getContext()
调用之前进行修补.
The key for this to work is to patch before any other code uses the getContext()
call.
使用风险自负!
这篇关于如何在纯JavaScript中覆盖本机JS函数(canvas的getContext())?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!