CodexBloom - Programming Q&A Platform

HTML5 <canvas> element scenarios to render after dynamic resizing in React application

👀 Views: 2 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-06
html canvas react javascript

I'm working with an scenario where my HTML5 `<canvas>` element does not render correctly after resizing dynamically in my React application. I'm using the latest version of React (v17.0.2) and the canvas is set up to draw some shapes based on user inputs. However, whenever the window is resized, the canvas appears blank, and I see the following behavior in the console: `Uncaught TypeError: want to read properties of null (reading 'getContext')`. Here's a simplified version of my component: ```javascript import React, { useRef, useEffect } from 'react'; const CanvasComponent = () => { const canvasRef = useRef(null); const draw = (ctx) => { ctx.fillStyle = '#000'; ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height); ctx.fillStyle = '#f00'; ctx.fillRect(50, 50, 100, 100); }; const resizeCanvas = () => { const canvas = canvasRef.current; const ctx = canvas.getContext('2d'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; draw(ctx); }; useEffect(() => { const canvas = canvasRef.current; const ctx = canvas.getContext('2d'); draw(ctx); window.addEventListener('resize', resizeCanvas); return () => window.removeEventListener('resize', resizeCanvas); }, []); return <canvas ref={canvasRef} style={{ border: '1px solid black' }} />; }; export default CanvasComponent; ``` I've ensured that `canvasRef.current` is populated before calling `getContext`, but it seems that during the resize event, the component might be unmounted or not fully rendered, leading to the `null` reference. I've tried adding a check for `canvasRef.current` before accessing it, but it still results in a blank canvas upon resizing. Is there a proper way to handle dynamic resizing with the canvas in a React environment? Any suggestions would be greatly appreciated! I'm working on a CLI tool that needs to handle this. Is there a better approach? My development environment is macOS.