Looking for a library that allows you to create simple drawings on canvas, I couldn’t find a satisfactory library for React, hence we will create our own. Today, we will build a simple library based on the HTML canvas element, that allow users to draw strokes with mouse or touch.
Let’s get started
To start quickly, I used the create-react-library package, which automates the process of creating and publishing React library. You can read more about this library in the docs, I used default config with the command:
npx create-react-library
First of all, I cleaned boilerplate code (src/index.js) and export a simple canvas component with customizable width and height.
Then, I added mouse and touch event listeners to the canvas element, which will have code for drawing onto canvas. We need to track mouse up and down events to decide whether to draw strokes. Mouse move to track position where we draw on the canvas. Additionally, component tracks the equivalents of these events for touchable devices. I also need the canvas ref and state variables, to determine if a user is drawing on canvas and the second one for mouse position tracking.
Listeners for mouse up and down are responsible for managing the drawing state. On mouse down, I also set mouse position on the canvas to get the start point of the drawing stroke.
Mouse move listener get current mouse position and draw stroke line on the canvas from the position before which is save in position state. Every listener use React useCallback hook to cache calculation when the same input occurs.
With the above steps, we get a simple drawing application. Whenever we click mouse down or touch and move on the canvas the line is being written.
Last, but not least I published the application as an npm package with few additional features that you can find in the app example.
References
- Example
- react-canvas-paint
- GitHub repository
Thanks For Reading ;)