Created
July 8, 2021 15:58
-
-
Save danrossi/8647416b850074dd206d5c963c214440 to your computer and use it in GitHub Desktop.
requestVideoFrameCallback with legacy mode to requestAnimationFrame
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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