[我正在学习有关对html5 canvas使用react的教程。作者正在使用类的基础组件,因此在呈现方法updateCanvas()时使用componentDidMount。
我正在使用基于函数的组件以及挂钩。因此,当方法drawTree,Branch和Leaf呈现时,我正在使用useEffect。
我在浏览器中收到一条错误消息'TypeError:ctx.translate不是一个函数,但是在sandbox中我没有收到任何错误消息,但是我的组件未渲染。另外,在我的代码编辑器中,.getContext('2D')显示为灰色,当我将鼠标悬停在它上面时,会收到一条消息“未解析的函数或方法”。
您应使用.current
参考的ctx
键进行访问。例如:
function drawTree() {
ctx.strokeStyle = "#fff";
ctx.beginPath();
ctx.translate(state.centerX, state.bottom);
branch(...state);
ctx.stroke();
}
应该是:
function drawTree() {
ctx.current.strokeStyle = "#fff";
ctx.current.beginPath();
ctx.current.translate(state.centerX, state.bottom);
branch({ ...state }); // Fixed this line too, `branch` is taking an object as its argument.
ctx.current.stroke();
}