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,28 +3,43 @@ class Icon {
this.url = url; this.url = url;
this.svgContent = ''; this.svgContent = '';
this.svgLoaded = false; this.svgLoaded = false;
this.load() this.cacheCanvas = null; // Offscreen canvas for caching
this.cacheContext = null;
this.cacheColor = null;
this.load();
} }
async load() { async load() {
return fetch(this.url) try {
.then(response => response.text()) const response = await fetch(this.url);
.then(svgContent => { this.svgContent = await response.text();
this.svgContent = svgContent; this.svgLoaded = true;
this.svgLoaded = true; } catch (error) {
}) console.error('Error loading SVG:', error);
.catch(error => { this.svgLoaded = false;
console.error('Error loading SVG:', error); }
this.svgLoaded = false;
});
} }
render(ctx, x, y, w, h, color) { render(ctx, x, y, w, h, color) {
if (this.svgLoaded) { if (!this.svgLoaded) return; // Do nothing if SVG is not loaded
ctx.fillStyle = color
ctx.drawSvg(this.svgContent, x, y, w, h) 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);
} }
} }
export { Icon }; export { Icon };