Search code examples
reactjstypescriptsharepointweb-parts

Canvas wont draw anything - React, Typescript


I am totally new to TS and I am trying to do some simple drawing with canvas. I get no errors but nothing is showed not even the console log that is inside function.

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>
    );
  }
}

And I just don't know how to fix it. I will be thankful for any help.


Solution

  • Please have a try below code:

    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");
      }

    Test Result:

    enter image description here

    BR