CalebN99
CalebN99

Reputation: 99

Canvas.clearRect is not a function in React

Trying to add a bit of canvas animation in my Portfolio website, I'm copying a simple animation from another project but I'm having an issue. .clearRect isn't a function in 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);
  }

Upvotes: 0

Views: 593

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 187034

You aren't passing your drawing context when animate is called from requestAnimationFrame. It works the first time through, because you call this.animate(c); and pass c right into animate.

You need to create a function that captures c and passes it to the next frame.

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

Upvotes: 2

Related Questions