Canvas.clearRect не является функцией в React - PullRequest
1 голос
/ 25 января 2020

Пытаясь добавить немного анимации холста на моем веб-сайте 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);
  }

1 Ответ

2 голосов
/ 25 января 2020

Вы не передаете свой контекст рисования, когда animate вызывается из requestAnimationFrame. Это работает с первого раза, потому что вы вызываете this.animate(c); и передаете c прямо в animate.

Вам необходимо создать функцию, которая захватывает c и передает ее в следующий кадр.

requestAnimationFrame(() => this.animate(c));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...