Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dsebastien/417025e685e7f1ddf52056eac7cdf3a7 to your computer and use it in GitHub Desktop.
Save dsebastien/417025e685e7f1ddf52056eac7cdf3a7 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);
const draw = (ctx: CanvasRenderingContext2D, frameCount: number) => {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height)
ctx.fillStyle = '#000000'
ctx.beginPath()
ctx.arc(50, 100, 20*Math.sin(frameCount*0.05)**2, 0, 2*Math.PI)
ctx.fill()
}
// 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;
}
let frameCount = 0
let animationFrameId = 0;
//Our draw came here
const render = () => {
frameCount++
draw(ctx, frameCount)
animationFrameId = window.requestAnimationFrame(render)
}
render()
return () => {
window.cancelAnimationFrame(animationFrameId)
}
}, [draw]);
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