Created
June 21, 2021 22:07
-
-
Save dsebastien/a1f58881e4bd0465a576be47b5e4bc63 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useRef } from 'react'; | |
export function App() { | |
// Use a ref to access the Canvas | |
const canvasRef = useRef<HTMLCanvasElement>(null); | |
// Use a ref to keep access to the Canvas Context | |
const canvasCtxRef = useRef<CanvasRenderingContext2D | null>(null); | |
// Only try to initialize the context once the Canvas DOM is ready | |
// hence the useEffect hook | |
useEffect(() => { | |
// At this point the canvas should be accessible through the ref | |
const canvas = canvasRef.current; | |
if(!canvas) { | |
return; | |
} | |
canvasCtxRef.current = canvas.getContext('2d'); | |
const ctx = canvasCtxRef.current; | |
if(!ctx) { | |
return; | |
} | |
ctx.beginPath(); | |
ctx.arc(95, 50, 40, 0, 2 * Math.PI); | |
ctx.stroke(); | |
}, []); | |
return ( | |
<div> | |
<canvas ref={canvasRef} id="canvas" width={640} height={480} tabIndex={0} aria-label="Second Brain">Alternative content describing what the canvas displays.</canvas> | |
</div> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment