|
24 | 24 | // Insert canvas as first child |
25 | 25 | card.insertBefore(canvas, card.firstChild); |
26 | 26 |
|
27 | | - // Function to draw the sketchy background |
28 | | - function drawCard() { |
29 | | - const rect = card.getBoundingClientRect(); |
30 | | - const width = card.offsetWidth; |
31 | | - const height = card.offsetHeight; |
32 | | - |
| 27 | + // Function to draw the sketchy background with given dimensions |
| 28 | + function drawCard(width, height) { |
33 | 29 | // Set canvas size |
34 | 30 | canvas.width = width; |
35 | 31 | canvas.height = height; |
|
53 | 49 | }); |
54 | 50 | } |
55 | 51 |
|
56 | | - // Draw initially |
57 | | - drawCard(); |
58 | | - |
59 | | - // Redraw on window resize |
60 | | - let resizeTimeout; |
61 | | - window.addEventListener('resize', () => { |
62 | | - clearTimeout(resizeTimeout); |
63 | | - resizeTimeout = setTimeout(drawCard, 100); |
| 52 | + // Use ResizeObserver for efficient resize handling (no forced reflow) |
| 53 | + const resizeObserver = new ResizeObserver(entries => { |
| 54 | + for (const entry of entries) { |
| 55 | + const { width, height } = entry.contentRect; |
| 56 | + if (width > 0 && height > 0) { |
| 57 | + drawCard(Math.round(width), Math.round(height)); |
| 58 | + } |
| 59 | + } |
64 | 60 | }); |
| 61 | + resizeObserver.observe(card); |
65 | 62 |
|
66 | 63 | // Redraw when theme changes (theme is set on <html>) |
67 | | - const observer = new MutationObserver(() => { |
68 | | - drawCard(); |
| 64 | + const themeObserver = new MutationObserver(() => { |
| 65 | + const width = card.offsetWidth; |
| 66 | + const height = card.offsetHeight; |
| 67 | + if (width > 0 && height > 0) { |
| 68 | + drawCard(width, height); |
| 69 | + } |
69 | 70 | }); |
70 | 71 |
|
71 | | - observer.observe(document.documentElement, { |
| 72 | + themeObserver.observe(document.documentElement, { |
72 | 73 | attributes: true, |
73 | 74 | attributeFilter: ['data-theme'] |
74 | 75 | }); |
|
0 commit comments