Skip to content

Commit 38e900a

Browse files
Optimization: use observer to find out if canvas is in viewport
1 parent b94cdcf commit 38e900a

File tree

2 files changed

+13
-7
lines changed

2 files changed

+13
-7
lines changed

src/lib/FastImageSequence.ts

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@ export class FastImageSequence {
7777
private container: HTMLElement;
7878
private resizeObserver: ResizeObserver;
7979
private mutationObserver: MutationObserver;
80+
private inViewportObserver: IntersectionObserver;
8081
private clearCanvas: boolean = true;
8182
private speed: number = 0;
8283
private prevFrame: number = 0;
@@ -87,6 +88,7 @@ export class FastImageSequence {
8788
private initialized: boolean = false;
8889
private posterImage: HTMLImageElement | undefined;
8990
private timeFrameVisible: number = 0;
91+
private inViewport: boolean = false;
9092

9193
/**
9294
* Creates an instance of FastImageSequence.
@@ -138,6 +140,13 @@ export class FastImageSequence {
138140
});
139141
this.mutationObserver.observe(container, {childList: true});
140142

143+
this.inViewportObserver = new IntersectionObserver((entries) => {
144+
entries.forEach(entry => {
145+
this.inViewport = entry.isIntersecting;
146+
});
147+
});
148+
this.inViewportObserver.observe(this.canvas);
149+
141150
// init all frames
142151
this.frames = Array.from({length: this.options.frames}, (_, index) => new Frame(index));
143152
this.log = this.options.showDebugInfo ? console.log : () => {
@@ -311,6 +320,7 @@ export class FastImageSequence {
311320

312321
this.resizeObserver.disconnect();
313322
this.mutationObserver.disconnect();
323+
this.inViewportObserver.disconnect();
314324

315325
this.container.removeChild(this.canvas);
316326
if (this.logElement) {
@@ -390,13 +400,9 @@ export class FastImageSequence {
390400
this.frame += this.speed * dt;
391401
this.frame = this.wrapFrame(this.frame);
392402

393-
const index = this.index;
394-
395-
// check if canvas is in viewport
396-
const rect = this.canvas.getBoundingClientRect();
397-
const inViewport = rect.top < window.innerHeight && rect.bottom > 0;
398403

399-
if (inViewport) {
404+
if (this.inViewport) {
405+
const index = this.index;
400406
// find the best matching loaded frame, based on current index and direction
401407
// first set some sort of priority
402408
this.frames.forEach((frame) => {

src/lib/LogToScreen.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,5 +17,5 @@ export function createLogElement() {
1717
}
1818

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

0 commit comments

Comments
 (0)