Canvas 不会画任何东西 - React, Typescript

Canvas wont draw anything - React, Typescript

我是 TS 的新手,我正在尝试用 canvas 做一些简单的绘图。我没有收到任何错误,但即使是函数内部的控制台日志也没有显示任何内容。

function gameLoader() {
  const gameCanvas = document.getElementById("gameCanvas") as HTMLCanvasElement;
  var ctx = gameCanvas.getContext("2d");
  ctx.fillStyle = "blue";
  ctx.fillRect(0, 0, 150, 75);
  console.log(document.getElementById("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXxx"));
}

export default class SnakeTheGame extends React.Component<
  ISnakeTheGameProps,
  {}
> {
  public render(): React.ReactElement<ISnakeTheGameProps> {
    return (
      <div className={styles.snakeTheGame} id="gameWindow">
        <canvas
          id={"gameCanvas"}
          height="500px"
          width="500px"
          onLoad={() => gameLoader()}
        ></canvas>
      </div>
    );
  }
}

而且我只是不知道如何修复它。如果有任何帮助,我将不胜感激。

canvas onload 仅在加载 smth 时触发,因此如果将加载程序函数放在 onload 中,它永远不会 运行

这是一个可能的解决方案

function gameLoader(gameCanvas: HTMLCanvasElement) {
  var ctx = gameCanvas.getContext("2d");
  ctx.fillStyle = "blue";
  ctx.fillRect(0, 0, 150, 75);
  console.log(document.getElementById("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXxx"));
}

export default class SnakeTheGame extends React.Component<
  ISnakeTheGameProps,
  {}
> {
  public render(): React.ReactElement<ISnakeTheGameProps> {
    const ref = useRef<HTMLCanvasElement>();
    useEffect(() => gameLoader(ref.current), []);
    return (
      <div className={styles.snakeTheGame} id="gameWindow">
        <canvas
          ref={ref}
          height="500px"
          width="500px"
        ></canvas>
      </div>
    );
  }
}

请尝试以下代码:

export default class Testcanvas extends React.Component<ITestcanvasProps, {}> {
  public render(): React.ReactElement<ITestcanvasProps> {
    return (
      <div className={styles.testcanvas}>
        <canvas
          ref="canvas"
          height="500px"
          width="500px"
        ></canvas>
      </div>
    );
  }

  public componentDidMount() {
    this.gameLoader();
  }

  private gameLoader(): void {
    const ctx = (this.refs.canvas as HTMLCanvasElement).getContext('2d');
    ctx.fillStyle = "blue";
    ctx.fillRect(0, 0, 150, 75);
    console.log("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXxx");
  }

测试结果:

BR