I'll create a simple canvas component for you using React and Next.js. This component will allow you to draw on a canvas using your mouse. Here's the implementation:
This implementation creates a simple canvas drawing component. Here's a breakdown of what's happening:
Canvas
component in components/Canvas.tsx
. This component is a client-side component (note the "use client" directive) because it uses browser APIs and event handlers.Canvas
component takes width
and height
props to set the canvas dimensions.useRef
hook to get a reference to the canvas element, and useState
to keep track of whether the user is currently drawing.useEffect
hook, we set up the initial canvas context with some default styles.startDrawing
, stopDrawing
, and draw
functions to handle mouse events for drawing on the canvas.onMouseDown
, onMouseUp
, onMouseOut
, onMouseMove
) to enable drawing functionality.app/page.tsx
, we import and use the Canvas
component, setting its width to 500 pixels and height to 300 pixels.To use this canvas, you can:
You can further enhance this component by adding features like color selection, brush size adjustment, or the ability to save the drawing. Let me know if you'd like to add any additional functionality!
I'll add a clear button to the Canvas component that allows users to erase everything they've drawn. Here's the implementation:
I've added a clear button to your canvas component with the following changes:
Created a clearCanvas
function that:
clearRect
method to erase everything on the canvasbeginPath()
Updated the component's return statement to:
Now users can click the "Clear Canvas" button whenever they want to start over with a blank canvas. The button is positioned directly below the canvas for easy access.