首页 > 解决方案 > 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);
  }

标签: javascriptreactjscanvas

解决方案


animaterequestAnimationFrame. 它第一次通过,因为您调用this.animate(c);并直接传递canimate.

您需要创建一个函数来捕获c并将其传递给下一帧。

requestAnimationFrame(() => this.animate(c));

推荐阅读