热重载中断 WebGL2RenderingContext

Hot Reload breaks WebGL2RenderingContext

我有一个 webpack/typescript/webgl2-设置。我有一个代表WebGL2RenderingContext的class,如下所示:

import { isNullOrUndefined } from "util";

export class GraphixContext implements Context<WebGL2RenderingContext> {
  private gl: WebGL2RenderingContext;
  private canvas: HTMLCanvasElement;
  private constructor(
    context: WebGL2RenderingContext,
    canvas: HTMLCanvasElement
  ) {
    this.gl = context;
    this.canvas = canvas;
  }

  public getContext(): WebGL2RenderingContext {
    return this.gl;
  }
  public appendCanvas(id: string) {
    document.body.appendChild(this.canvas);
    this.canvas.id = id;
  }

  public static build(): GraphixContext {
    let canvas = document.createElement("canvas");
    const gl = canvas.getContext("webgl2");

    if (isNullOrUndefined(gl)) {
      throw new Error("WebGL could not be initialized");
    }
    return new GraphixContext(gl, canvas);
  }
}

我用命令

启动 webpack-dev-server
`"scripts": {
    "build": "webpack ",
    "watch": "webpack --watch",
    "start": "webpack-dev-server --open"
  },`

当我开始输入 GraphixContext.ts 时,热重载被激活并且 webpack 创建一个 bundle.js。但是,只有当我编辑 GraphixContext 中的代码时,才会显示以下错误。

  TS2345: Argument of type 'WebGLRenderingContext | CanvasRenderingContext2D' is not assignable to parameter of type 'WebGL2RenderingContext'.
  Type 'WebGLRenderingContext' is missing the following properties from type 'WebGL2RenderingContext': READ_BUFFER, UNPACK_ROW_LENGTH, UNPACK_SKIP_ROWS, UNPACK_SKIP_PIXELS, and 347 more.

我项目中的所有其他编辑工作正常。有人对此错误有解释吗?

这是类型错误。

问题在于您使用的任何类型系统认为 canvas.getContext 只能 return WebGLRenderingContextCanvasRenderContext2D 而不是 WebGL2RenderingContext所以当你调用 GraphixContext 构造函数时,它认为 gl 是错误的类型。

改变这个

 const gl = canvas.getContext("webgl2");

到这个?

 const gl = <WebGL2RenderingContext>canvas.getContext("webgl2");

或者修正你对 canvas.getContext 的定义,这样它就可以 return 一个 WebGL2RenderingContext

问题可能出在这方面

https://github.com/Microsoft/TypeScript/blob/b7d7d5f7b39a5b9619c77590e5fe7f434ed68f1e/src/lib/dom.generated.d.ts#L5998

"webgl2"

没有条目