Skip to content

Instantly share code, notes, and snippets.

@dsebastien
Created June 21, 2021 22:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dsebastien/a1f58881e4bd0465a576be47b5e4bc63 to your computer and use it in GitHub Desktop.
Save dsebastien/a1f58881e4bd0465a576be47b5e4bc63 to your computer and use it in GitHub Desktop.
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