From c79476e7a9ab66ce8da82a867bce0d6fac0d264d Mon Sep 17 00:00:00 2001 From: Skyler Lehmkuhl Date: Thu, 23 Jan 2025 04:55:18 -0500 Subject: [PATCH] Cache icon rendering to improve performance --- src/icon.js | 45 ++++++++++++++++++++++++++++++--------------- 1 file changed, 30 insertions(+), 15 deletions(-) diff --git a/src/icon.js b/src/icon.js index 6f49db5..1dd5890 100644 --- a/src/icon.js +++ b/src/icon.js @@ -3,28 +3,43 @@ 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); } } -export { Icon }; \ No newline at end of file +export { Icon };