<canvas width="100" height="100"></canvas>DedicatedWorkerGlobalScope: cancelAnimationFrame() method
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
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);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);
}
}
});