Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cache loaded dom images on Image class so the playground-editor doesn't have to reload them often #13388

Merged
merged 5 commits into from
Jan 10, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Limit cache
  • Loading branch information
carolhmj committed Dec 28, 2022
commit ec988ff25c704efa6492e0615e277f36d0c6df9a
31 changes: 21 additions & 10 deletions packages/dev/gui/src/2D/controls/image.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@ export class Image extends Control {
key: string;
} = { data: null, key: "" };

public static SourceImgCache = new Map<string, IImage>();
public static SourceImgCache = new Map<string, { img: IImage; lastUsed: number }>();
public static SourceImgCacheMaxSize = 100;

/**
* Observable notified when the content is loaded
Expand Down Expand Up @@ -484,7 +485,6 @@ export class Image extends Control {
}

private _onImageLoaded(): void {
console.log(this.name, "image loaded");
this._imageDataCache.data = null;
this._imageWidth = this._domImage.width;
this._imageHeight = this._domImage.height;
Expand Down Expand Up @@ -533,19 +533,30 @@ export class Image extends Control {
throw new Error("Invalid engine. Unable to create a canvas.");
}
if (value && Image.SourceImgCache.has(value)) {
console.log("cache hit for", value);
this._domImage = Image.SourceImgCache.get(value)!;
const cachedData = Image.SourceImgCache.get(value)!;
this._domImage = cachedData.img;
// Update the last used time
cachedData.lastUsed = Date.now();
this._onImageLoaded();
return;
// this._domImage.onload = () => {
// this._onImageLoaded();
// };
return;
}
this._domImage = engine.createCanvasImage();
if (value) {
console.log("populate image cache");
Image.SourceImgCache.set(value, this._domImage);
if (Image.SourceImgCache.size > Image.SourceImgCacheMaxSize) {
// If the cache is at max capacity, delete the oldest image
let oldestKey = "";
let oldestTime = -Number.MAX_VALUE;

Image.SourceImgCache.forEach((value, key) => {
if (value.lastUsed < oldestTime) {
oldestTime = value.lastUsed;
oldestKey = key;
}
});

Image.SourceImgCache.delete(oldestKey);
}
Image.SourceImgCache.set(value, { img: this._domImage, lastUsed: Date.now() });
}

this._domImage.onload = () => {
Expand Down