requestanimationframe 在每个循环中重置一个增量变量

request animation frame resetting an incremented variable each loop

我正在尝试将 HTML canvas 上的图像旋转 40 度,作为请求动画帧循环的一部分,每次旋转 1 度。但是,一旦 运行,图像的旋转量似乎会在每次刷新页面时 运行 完全改变,偶尔会完全按照我想要的方式工作。调试时,'counter' 变量似乎正在重置每个循环,尽管它已递增。我不知道是什么导致了这种情况,语言的新手,任何帮助将不胜感激。

  let counter = 0;  //sets counter to 0

requestAnimationFrame(spin)  //initialises the loop

function spin(){

    rc.clearRect(0,0,window.innerWidth, window.innerHeight)
    rc.save();
    rc.translate(frameWidth/2, frameHeight/2);       //translates canvas for rotation (rc is canvas context)
    const angle = -1;     //angle to rotate by each loop
    rc.rotate(radCalc(angle));      //actual rotation (function is angle * PI/180)

    counter++  //Counter should keep track of each loop, yet resets every time?

    rc.translate(-frameWidth/2, -frameHeight/2)   //restore canvas
    rc.drawImage(dialSpinImage, column * frameWidth, row *frameHeight, frameWidth, frameHeight, 0, 0, frameWidth, frameHeight )   //draw image
    rc.restore

    let stop = requestAnimationFrame(spin);  //get animation frame ID

    if (counter < 40){   //checks canvas has not rotated over 40 degrees

        requestAnimationFrame(spin)

    }

    else {    //if it has, stop the loop

        cancelAnimationFrame(stop)

    }

}

}

您的代码中有几个较小的错误。让我们通过所有的'em:

1

在函数 spin() 中有如下一行:

const angle = -1;

这最终会在每次调用 spin() 时将角度重置为 -1。该变量需要在函数范围之外定义,并在函数内部递减。

2

let stop = requestAnimationFrame(spin);  //get animation frame ID

if (counter < 40){   //checks canvas has not rotated over 40 degrees

    requestAnimationFrame(spin)

}

这并不像您预期​​的那样有效。第一行不只是 return 您最终可能使用的帧 ID - 不 - 它会立即调用请求的函数 spin() 。像角度变量一样,它需要在函数外定义一次。

考虑到以上所有内容,这是您的代码的一个工作示例:

let canvas = document.getElementById("canvas");
let rc = canvas.getContext("2d");
let dialSpinImage = new Image();
let frameWidth = canvas.width;
let frameHeight = canvas.height;
let angle = 0;
let reqAnim;
let counter = 0;

dialSpinImage.onload = function() {
  start();
}
dialSpinImage.src = "https://picsum.photos/id/237/60/60";

function start() {
  reqAnim = requestAnimationFrame(spin);
}

function spin() {
  rc.clearRect(0, 0, frameWidth, frameHeight);
  rc.save();
  rc.translate(frameWidth / 2, frameHeight / 2); //translates canvas for rotation (rc is canvas context)
  angle -= 1;
  rc.rotate(angle * Math.PI / 180);
  counter++;


  rc.translate(-frameWidth / 2, -frameHeight / 2) //restore canvas
  rc.drawImage(dialSpinImage, 0, 0, frameWidth, frameHeight) //draw image
  rc.restore();



  if (counter < 40) { //checks canvas has not rotated over 40 degrees

    reqAnim = requestAnimationFrame(spin)

  } else { //if it has, stop the loop

    cancelAnimationFrame(reqAnim);
 
  }

}
<canvas id="canvas"></canvas>