我想当画布元素调用'getContext('webgl'('时,返回'null'值。
我试图找到WebGLRenderingContext
原型并更新它,但我找不到它。
WebGLRenderingContext
和WebGLRenderingContextBase
没有prototype.getContext
.
如何更改它返回到"空"值?
我已经在下面进行了测试..
var test = document.createElement('canvas');`
test.getContext("webgl");`
这将返回WebGLRenderingContext
对象...
请帮我:)
乱原生原型?好吧,我想你知道你在做什么。如果是这样,并且您真的想覆盖getContext
原型方法,您可以使用简单的装饰器来实现HTMLCanvasElement.prototype.getContext
:
HTMLCanvasElement.prototype.getContext = function (orig) {
return function(type) {
return type !== "webgl" ? orig.apply(this, arguments) : null
}
}(HTMLCanvasElement.prototype.getContext)
因此,对于任何上下文,例如 2d、3d,它都可以正常工作,但对于"webgl",它会给出 null
.不知道,为什么你需要这个,不过。
不知道为什么要这样做,但假设你确切地知道你在做什么™,你可以这样做:
// 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()
做类似的事情。
要使其正常工作,关键是在任何其他代码使用 getContext()
调用之前进行修补。
使用风险自负!