【问题标题】:Canvas wont draw anything - React, Typescript画布不会画任何东西 - React,Typescript
【发布时间】:2020-12-19 09:38:33
【问题描述】:

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

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

我只是不知道如何解决它。我将不胜感激。

【问题讨论】:

  • SnakeTheGame 是否被任何东西渲染?您的应用是否正在渲染到 DOM 中?
  • 是的,Canvas 有正确的尺寸和 ID。 (是 sharepoint webpart)
  • 使用 ref,不要使用 getElementById

标签: reactjs typescript sharepoint web-parts


【解决方案1】:

canvas onload 仅在加载时触发,因此如果您将加载器函数置于 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>
    );
  }
}

【讨论】:

  • 感谢您的推荐。对不起,我有一段时间没来了。尝试此操作时遇到一些错误,但现在我了解画布 onLoad。非常感谢您的宝贵时间。
【解决方案2】:

请试试下面的代码:

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

【讨论】:

    猜你喜欢
    • 2011-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-25
    • 1970-01-01
    • 2016-07-10
    • 1970-01-01
    相关资源
    最近更新 更多