First, we need to create a new react app, so I will run this in the terminal.
Now this will create a new folder called drawing-app. Now we change our directory.
If we run the ls command you should see this.
We’re ready to go ?
Starting the app
Now we have our app ready, we will start the app.
Now open localhost:3000 in your browser. You should see something like this.
Now we open our editor and remove all the code in App.js and put this code.
First, we will create the canvas.
Then, we will use the useRef hook to select the canvas element.
Now we have our canvas, now we will add the functionality to draw it. To do this we will create 2 functions one for setting the mouse position and one for drawing. Before we do that, we need to set our states.
The function to save the position
Now we add event listeners to our canvas.
Now every time we move the mouse, the state gets updated.
Function to draw
Now before we create the Draw function, we need to save 2 states.
Color of the pen
Size of the pen
We can use the hook useState again.
Now we have our states. Let’s create the function now.
Now we add our event listener to the canvas.
Now save the file and open localhost:3000. Now you can draw some stuff. But wait, we need to add the controls.
Now we have made our drawing app! ?That’s all for now. See you next time. ?
And if you need to copy-paste the full code here it is.