Cache icon rendering to improve performance

This commit is contained in:
Skyler Lehmkuhl 2025-01-23 04:55:18 -05:00
parent ad1da5b349
commit c79476e7a9
1 changed files with 30 additions and 15 deletions

View File

@ -3,27 +3,42 @@ class Icon {
this.url = url;
this.svgContent = '';
this.svgLoaded = false;
this.load()
this.cacheCanvas = null; // Offscreen canvas for caching
this.cacheContext = null;
this.cacheColor = null;
this.load();
}
async load() {
return fetch(this.url)
.then(response => response.text())
.then(svgContent => {
this.svgContent = svgContent;
this.svgLoaded = true;
})
.catch(error => {
console.error('Error loading SVG:', error);
this.svgLoaded = false;
});
try {
const response = await fetch(this.url);
this.svgContent = await response.text();
this.svgLoaded = true;
} catch (error) {
console.error('Error loading SVG:', error);
this.svgLoaded = false;
}
}
render(ctx, x, y, w, h, color) {
if (this.svgLoaded) {
ctx.fillStyle = color
ctx.drawSvg(this.svgContent, x, y, w, h)
if (!this.svgLoaded) return; // Do nothing if SVG is not loaded
if (!this.cacheCanvas || this.cacheCanvas.width !== w || this.cacheCanvas.height !== h || this.cacheColor !== color) {
// Create or update the offscreen canvas for caching
this.cacheCanvas = document.createElement('canvas');
this.cacheCanvas.width = w;
this.cacheCanvas.height = h;
this.cacheContext = this.cacheCanvas.getContext('2d');
// Draw the SVG onto the offscreen canvas
this.cacheContext.clearRect(0, 0, w, h); // Clear previous contents
this.cacheContext.fillStyle = color;
this.cacheColor = color
this.cacheContext.drawSvg(this.svgContent, 0, 0, w, h);
}
// Draw the cached result onto the main canvas
ctx.drawImage(this.cacheCanvas, x, y);
}
}