Skip to content

Instantly share code, notes, and snippets.

@danrossi
Created July 8, 2021 15:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danrossi/8647416b850074dd206d5c963c214440 to your computer and use it in GitHub Desktop.
Save danrossi/8647416b850074dd206d5c963c214440 to your computer and use it in GitHub Desktop.
requestVideoFrameCallback with legacy mode to requestAnimationFrame
const supportsFrameCallback = 'requestVideoFrameCallback' in HTMLVideoElement.prototype,
requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame || window.msRequestAnimationFrame,
cancelAnimationFrame = window.cancelAnimationFrame || window.mozCancelAnimationFrame;
export default class VideoAnimation {
constructor(callback, video) {
this.callback = callback,
this.video = video,
this.animationID = null,
this.running = false;
}
setCallback(callback) {
this.callback = callback;
}
animateLegacy() {
this.callback();
this.animationID = requestAnimationFrame(() => this.animateLegacy());
}
animate(now, metadata) {
this.callback(now, metadata);
this.video.requestVideoFrameCallback(this.animateRef);
}
start() {
this.stop();
if (supportsFrameCallback) {
this.animateRef = (now, metadata) => this.animate(now, metadata);
this.video.requestVideoFrameCallback(this.animateRef);
} else {
this.animateLegacy();
}
this.running = true;
}
stop() {
this.running = false;
if (supportsFrameCallback) {
this.animateRef = () => {};
} else {
cancelAnimationFrame(this.animationID && this.animationID.data && this.animationID.data.handleId || this.animationID);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment