大网数据广告活动
Web 标准与前端开发

DedicatedWorkerGlobalScope: cancelAnimationFrame() method

· 52CE 我爱测

The **`cancelAnimationFrame()`** method of the DedicatedWorkerGlobalScope interface cancels an animation frame request previously scheduled through a call to DedicatedWorkerGlobalScope.requestAnimationFrame().

Web Workers APIdedicated

The cancelAnimationFrame() method of the DedicatedWorkerGlobalScope interface cancels an animation frame request previously scheduled through a call to DedicatedWorkerGlobalScope.requestAnimationFrame().

Calling the cancelAnimationFrame() method requires the current worker to have an associated owner Window. That means that the current worker must be created by Window or by a dedicated worker that also has an associated owner Window.

Syntax

cancelAnimationFrame(handle)

Parameters

  • handle
    • : The ID value returned by a call to DedicatedWorkerGlobalScope.requestAnimationFrame(); the call must have been made in the same worker.

Return value

None (undefined).

Exceptions

  • NotSupportedError DOMException
    • : Thrown if the method is not supported by the current worker.

Examples

Here's a complete example showing how to use requestAnimationFrame() in a dedicated worker with an OffscreenCanvas.

The HTML should contain:

<canvas width="100" height="100"></canvas>

It should link to the following JavaScript:

const worker = new Worker("worker.js");

// Transfer canvas control to the worker
const offscreenCanvas = document
  .querySelector("canvas")
  .transferControlToOffscreen();

// Start the animation
worker.postMessage(
  {
    type: "start",
    canvas: offscreenCanvas,
  },
  [offscreenCanvas],
);

// Stop the animation after 5 seconds
setTimeout(() => {
  worker.postMessage({
    type: "stop",
  });
}, 5000);

worker.js:

let ctx;
let pos = 0;
let animationId;
let isRunning = false;
let lastTime = 0;

function draw(currentTime) {
  if (!isRunning) return;

  // Calculate delta time for smooth animation
  if (lastTime === 0) lastTime = currentTime;
  const deltaTime = (currentTime - lastTime) / 1000;
  lastTime = currentTime;

  // Clear and draw the moving rectangle
  ctx.clearRect(0, 0, 100, 100);
  ctx.fillRect(pos, 0, 10, 10);
  pos += 50 * deltaTime; // Move 50 pixels per second

  // Loop the animation
  if (pos > 100) pos = -10;

  animationId = self.requestAnimationFrame(draw);
}

self.addEventListener("message", (e) => {
  if (e.data.type === "start") {
    const transferredCanvas = e.data.canvas;
    ctx = transferredCanvas.getContext("2d");
    isRunning = true;
    lastTime = 0;
    animationId = self.requestAnimationFrame(draw);
  }
  if (e.data.type === "stop") {
    isRunning = false;
    if (animationId) {
      self.cancelAnimationFrame(animationId);
    }
  }
});

On the main thread, we start by transferring the control of a canvas element to an OffscreenCanvas, using HTMLCanvasElement.transferControlToOffscreen() and send a message to "start" its work to the worker, with the offscreen canvas.

In the worker file (worker.js), we handle the animation logic. When receiving the "start" message, the worker starts the animation, moving the rectangle from left to right. Upon reception of a "stop" message, it will stop the animation.

Finally, the main thread can send a "stop" message to the worker to stop the animation after a delay, allowing the animation to be visible before stopping.

Specifications

Browser compatibility

See also

  • DedicatedWorkerGlobalScope.requestAnimationFrame()
  • Window.cancelAnimationFrame()

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。