首页 > 解决方案 > 完成后在哪里调用cancelAnimationFrame?

问题描述

我无法识别 step() 函数中的一行来指示动画已完成。因此,我无法正确取消AnimationFrame。

问题:这是 cancelAnimationFrame() 不起作用的原因吗?如果是,我应该在哪一行代码中指示动画已经完成,以便我可以取消AnimationFrame?

var myRequestId;

function step() {

  // ... see https://codepen.io/jek/pen/RwwXBpz

  myRequestId = requestAnimationFrame(step);
  console.log("myRequestId", myRequestId);
}

myRequestId = requestAnimationFrame(step);

// Ref https://developer.mozilla.org/en-US/docs/Web/API/Window/cancelAnimationFrame
// todo: How do we stop it onComplete?
// question: where do we put a flag to indicate that it has completed?
//cancelAnimationFrame(myRequestId); // todo: If we uncomment this line the animation won't work at all

https://codepen.io/jek/pen/RwwXBpz

标签: javascriptcanvashtml5-canvasrequestanimationframecancelanimationframe

解决方案


你不需要运行cancelAnimationFrame,你可以有条件地运行requestAnimationFrame。

像这样:

function step() {
  ctx.setTransform(1, 0, 0, 1, 0, 0);
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.globalAlpha = 1;
  ctx.fillStyle = "#622";
  ctx.fillRect(0, (canvas.height - scale) / 2, canvas.width, scale);
  let running = false;
  for (var i = 0; i < text.length; i++) {
    ctx.fillStyle = "#ccc";
    ctx.textBaseline = "middle";
    ctx.textAlign = "center";
    ctx.setTransform(
      1,
      0,
      0,
      1,
      Math.floor((canvas.width - scale * (text.length - 1)) / 2),
      Math.floor(canvas.height / 2)
    );
    var o = offset[i];
    while (o < 0) o++;
    o %= 1;
    var h = Math.ceil(canvas.height / 2 / scale);
    for (var j = -h; j < h; j++) {
      var c = charMap[text[i]] + j - Math.floor(offset[i]);
      while (c < 0) c += chars.length;
      c %= chars.length;
      var s = 1 - Math.abs(j + o) / (canvas.height / 2 / scale + 1);
      ctx.globalAlpha = s;
      ctx.font = scale * s + "px Helvetica";
      ctx.fillText(chars[c], scale * i, (j + o) * scale);
    }
    offset[i] += offsetV[i];
    offsetV[i] -= breaks;
    if (offsetV[i] < endSpeed) {
      offset[i] = 0;
      offsetV[i] = 0;
    } else {
      running = true;
    }
  }
  if (running) {
    requestAnimationFrame(step);
  } else {
    console.log('animation stopped');
  }
}

现场演示


推荐阅读