[英]WebGL - How do I pass in the program parameter to gl.attachShader correctly in Typescript?
I create a program like so: 我创建一个像这样的程序:
const program: WebGLProgram = gl.createProgram();
Then eventually attempt to attach the shader to the program like so: 然后最终尝试将着色器附加到程序,如下所示:
gl.attachShader(program, vertexShader);
This throws the following error: 这将引发以下错误:
Error: TypeError: Failed to execute 'attachShader' on 'WebGL2RenderingContext': parameter 1 is not of type 'WebGLProgram'.
错误:类型错误:无法在'WebGL2RenderingContext'上执行'attachShader':参数1不是'WebGLProgram'类型。
Upon observing the program, typeof program
is equal to object
, so the error makes sense. 在观察程序时,
typeof program
等于object
,因此该错误是有意义的。
If I try and do the following, which works if I change the program type to any since typeof program.program
is equal to WebGLProgram
: 如果我尝试执行以下操作,则由于
typeof program.program
等于WebGLProgram
,所以我将程序类型更改为任何类型时都可以WebGLProgram
:
gl.attachShader(program.program, vertexShader);
It will throw the following error: 它将引发以下错误:
Property 'program' does not exist on type 'WebGLProgram'.
类型“ WebGLProgram”上不存在属性“程序”。
What is the correct way to resolve this issue in Typescript? 解决打字稿中此问题的正确方法是什么? I would prefer not to write
program.program
with the any type. 我宁愿不要编写任何类型的
program.program
。
The error is not thrown by the TypeScript compiler, it is thrown by the browser runtime. 该错误不是由TypeScript编译器引发的,而是由浏览器运行时引发的。 If
strictNullChecks
is enabled in the tsconfig.json
compilerOptions
, you'll see the return type of WebGLRenderingContext/createProgram is WebGLProgram | null
如果在
tsconfig.json
compilerOptions
strictNullChecks
中启用了tsconfig.json
, tsconfig.json
看到WebGLRenderingContext / createProgram的返回类型为WebGLProgram | null
WebGLProgram | null
, then you must first check that program
is not null: WebGLProgram | null
,那么您必须首先检查program
是否为null:
const canvas = document.createElement("canvas");
const gl = canvas.getContext("webgl");
if (gl) {
const program = gl.createProgram();
const vertexShader = gl.createShader(gl.VERTEX_SHADER);
if (program && vertexShader) {
gl.attachShader(program, vertexShader);
} else {
throw new Error("WebGL createProgram or createShader failed!");
}
} else {
throw new Error("WebGL seems not supported!");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.