Skip to content

Instantly share code, notes, and snippets.

@positlabs
Created December 16, 2022 15:01
Show Gist options
  • Select an option

  • Save positlabs/4da1f1f61a30c462c77c44db6889706a to your computer and use it in GitHub Desktop.

Select an option

Save positlabs/4da1f1f61a30c462c77c44db6889706a to your computer and use it in GitHub Desktop.

Revisions

  1. positlabs created this gist Dec 16, 2022.
    40 changes: 40 additions & 0 deletions FrameUpdateMonitor.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,40 @@
    /*
    Register a callback for when a video frame is updated
    Since video playback generally isn't 60fps, this can be used as a render optimization
    new FrameUpdateMonitor(videoElement, callback)
    */
    export class FrameUpdateMonitor {

    private _active: boolean = false
    public set active (bool){
    this._active = bool
    if(this._active) this.onFrame()
    }
    public get active(){
    return this._active
    }

    video: HTMLVideoElement
    lastTime: number = -1
    callback: Function

    constructor(video: HTMLVideoElement, callback: Function) {
    this.video = video
    this.callback = callback
    this.onFrame()
    }

    private onFrame() {
    if (this.active) requestAnimationFrame(this.onFrame.bind(this))
    var time = this.video.currentTime
    // console.log('onFrame', this.active, time, this.lastTime)
    if (time !== this.lastTime) {
    this.lastTime = time
    this.callback(time)
    }
    }

    }