reactjs - 画布不会画任何东西 - React,Typescript
问题描述
我对 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>
);
}
}
我只是不知道如何解决它。我会感谢任何帮助。
解决方案
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>
);
}
}
推荐阅读
- prolog - Prolog文字游戏打印描述重复输出
- c# - 如何使用 C# 在 excel 的下拉列表中选择一个项目?
- java - 无法将 BLOB 保存到数据库(ORA-01460:需要未实现或无意义的转换)
- python - 在 Python 中使用从父类继承的方法时返回子类的新实例
- javascript - 仅在 ipad 上使用 AJAX 在制表器上加载数据时出错
- javascript - 鼠标离开后CSS过渡到原始状态
- wpf - kiosk 模式下的 XML 文档异常出现错误
- android - 滚动时更新自定义列表视图失败
- gulp - Gulp 给出 SyntaxError: Unexpected identifier; 节点问题。苹果电脑
- javascript - jison:如何在 jison 文件中添加“require”?