javascript - Canvas.clearRect 不是 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);
}
解决方案
当animate
从requestAnimationFrame
. 它第一次通过,因为您调用this.animate(c);
并直接传递c
到animate
.
您需要创建一个函数来捕获c
并将其传递给下一帧。
requestAnimationFrame(() => this.animate(c));
推荐阅读
- python - 在训练我的神经网络后,如何从最后一个解码器层“logits”中提取图像?
- javascript - 使用扩展运算符克隆集导致 Gatsby 中的嵌套集
- python-3.x - Scrapy 规则:使用进程链接排除某些 url
- typescript - 在 Typescript 中定义为箭头函数的方法上调用 super.method() 时出错
- r - 使用反应数据集的模块内部的renderHighchart
- amazon-web-services - 如何创建自定义事件触发器以在创建新存储桶时调用 lambda?
- python - functionB的多线程线程直到function A的线程完成才开始,但是functionA的线程不等待functionB
- oracle - 不输入参数时忽略where子句中的日期范围参数
- python - ipywidgets 与 Jupyter Lab 1.0+ 版兼容?
- php - PHP密码验证,