簡體   English   中英

Canvas.clearRect 不是 React 中的函數

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM