[英]Canvas.clearRect is not a function in React
试图在我的 Portfolio 网站中添加一些画布动画,我正在从另一个项目复制一个简单的动画,但我遇到了问题。 .clearRect 不是 React 中的函数 :(
animate = c => {
requestAnimationFrame(this.animate);
c.clearRect(0, 0, 800, 600);
c.fillStyle = "white";
c.fillRect(this.state.positionX, this.state.positionY, 20, 20);
this.state.positionX += this.state.xSpeed;
this.state.positionY += this.state.ySpeed;
if (this.state.positionX === 780) this.setState({ xSpeed: -2 });
if (this.state.positionX === 0) this.setState({ xSpeed: 2 });
if (this.state.positionY === 0) this.setState({ ySpeed: 2 });
if (this.state.positionY === 580) this.setState({ xSpeed: -2 });
};
componentDidMount() {
const canvas = document.getElementById("canv");
const c = canvas.getContext("2d");
this.animate(c);
}
从requestAnimationFrame
调用animate
时,您没有传递绘图上下文。 它第一次运行,因为你调用this.animate(c);
并将c
传递给animate
。
您需要创建一个函数来捕获c
并将其传递给下一帧。
requestAnimationFrame(() => this.animate(c));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.