Created
May 29, 2022 08:36
-
-
Save honungsburk/7abbc68fe6adf9a01eea3016d5440daf to your computer and use it in GitHub Desktop.
React Canvas
This file contains hidden or 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"; | |
type CanvasProps = { | |
width: number; | |
height: number; | |
}; | |
export function Canvas(props: CanvasProps) { | |
const canvasRef = useRef<HTMLCanvasElement | null>(null); | |
const draw = (ctx: CanvasRenderingContext2D, canvas: HTMLCanvasElement) => { | |
ctx.clearRect(0, 0, canvas.width, canvas.height); | |
ctx.beginPath(); | |
ctx.arc(canvas.width / 2, canvas.height / 2, 4, 0, 2 * Math.PI, true); | |
ctx.fillStyle = "#FF6A6A"; | |
ctx.fill(); | |
}; | |
useEffect(() => { | |
if (canvasRef.current) { | |
const canvas = canvasRef.current; | |
const ctx = canvasRef.current.getContext("2d"); | |
if (ctx) { | |
let animationFrameId = 0; | |
const render = () => { | |
draw(ctx, canvas); | |
animationFrameId = window.requestAnimationFrame(render); | |
}; | |
render(); | |
return () => { | |
window.cancelAnimationFrame(animationFrameId); | |
}; | |
} | |
} | |
}, []); | |
return ( | |
<canvas | |
ref={canvasRef} | |
style={{ display: "inline-block" }} | |
width={props.width} | |
height={props.height} | |
> | |
Your browser does not support the HTML canvas tag. | |
</canvas> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment