Creating a Canvas Drawing library with React

Piotrek
2 min readMar 7, 2021

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.

Example from deployed library

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.

Code fragment with basic ReactCanvasPaint component

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.

Code fragment with canvas props and state variables

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.

Code fragment with onDown and onUp function

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.

Code fragment with onMove and drawLine function

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.

Drawing on the canvas example with a mouse on desktop

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 ;)

--

--

Piotrek
0 Followers

Web developer with a passion to learn new things.