Skip to content

Commit

Permalink
Optimization: use observer to find out if canvas is in viewport
Browse files Browse the repository at this point in the history
  • Loading branch information
reindernijhoff committed Jan 6, 2025
1 parent b94cdcf commit 38e900a
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 7 deletions.
18 changes: 12 additions & 6 deletions src/lib/FastImageSequence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ export class FastImageSequence {
private container: HTMLElement;
private resizeObserver: ResizeObserver;
private mutationObserver: MutationObserver;
private inViewportObserver: IntersectionObserver;
private clearCanvas: boolean = true;
private speed: number = 0;
private prevFrame: number = 0;
Expand All @@ -87,6 +88,7 @@ export class FastImageSequence {
private initialized: boolean = false;
private posterImage: HTMLImageElement | undefined;
private timeFrameVisible: number = 0;
private inViewport: boolean = false;

/**
* Creates an instance of FastImageSequence.
Expand Down Expand Up @@ -138,6 +140,13 @@ export class FastImageSequence {
});
this.mutationObserver.observe(container, {childList: true});

this.inViewportObserver = new IntersectionObserver((entries) => {
entries.forEach(entry => {
this.inViewport = entry.isIntersecting;
});
});
this.inViewportObserver.observe(this.canvas);

// init all frames
this.frames = Array.from({length: this.options.frames}, (_, index) => new Frame(index));
this.log = this.options.showDebugInfo ? console.log : () => {
Expand Down Expand Up @@ -311,6 +320,7 @@ export class FastImageSequence {

this.resizeObserver.disconnect();
this.mutationObserver.disconnect();
this.inViewportObserver.disconnect();

this.container.removeChild(this.canvas);
if (this.logElement) {
Expand Down Expand Up @@ -390,13 +400,9 @@ export class FastImageSequence {
this.frame += this.speed * dt;
this.frame = this.wrapFrame(this.frame);

const index = this.index;

// check if canvas is in viewport
const rect = this.canvas.getBoundingClientRect();
const inViewport = rect.top < window.innerHeight && rect.bottom > 0;

if (inViewport) {
if (this.inViewport) {
const index = this.index;
// find the best matching loaded frame, based on current index and direction
// first set some sort of priority
this.frames.forEach((frame) => {
Expand Down
2 changes: 1 addition & 1 deletion src/lib/LogToScreen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,5 @@ export function createLogElement() {
}

export function logToScreen(logElement: HTMLElement, log: string) {
logElement.innerText = `${log}`;
logElement.textContent = `${log}`;
}

0 comments on commit 38e900a

Please sign in to comment.