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

问题描述

我对TS完全陌生,我正在尝试使用画布进行一些简单的绘图。我没有收到任何错误,但是即使函数内部的控制台日志也没有显示。

function gameLoader() {
  const gameCanvas = document.getElementById("gameCanvas") as HTMLCanvasElement;
  var ctx = gameCanvas.getContext("2d");
  ctx.fillStyle = "blue";
  ctx.fillRect(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时触发,因此,如果将loader函数置于onload,它将永远不会运行

这是一个可能的解决方案

function gameLoader(gameCanvas: HTMLCanvasElement) {
  var ctx = gameCanvas.getContext("2d");
  ctx.fillStyle = "blue";
  ctx.fillRect(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,75);
    console.log("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXxx");
  }

测试结果:

enter image description here

BR

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...