I'm currently working on creating a rectangle within a canvas element. I've set the width of the div to match the width of the rectangle, but unfortunately, the rectangle is extending beyond the left side of the canvas container. My goal is to contain the canvas within the container and make its width equal to the width of the div.
Check out my code snippet below:
export default function App() {
const canvasRef = useRef<HTMLCanvasElement>(null);
const divRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const canvasReference = canvasRef.current;
const divReference = divRef.current;
const context = canvasReference?.getContext("2d");
if (context && divReference) {
context.strokeStyle = "#000";
context.strokeRect(0, 0, divReference.clientWidth, 45);
}
}, []);
return (
<div className="App" ref={divRef}>
<canvas className="timelineCanvas" ref={canvasRef}></canvas>
</div>
);
}
Feel free to explore the sandbox link