Introduction
Sometimes, we need to capture the user's signature using screen itself, like using touch pen, mouse or any other device which is compatible with like a kiosk where we need to capture the customer signature for the verification purpose or something like that.
For this requirement, different possibilities are there to implement such a thing and one of those is an HTML canvas where we can draw the free-hand drawing. Similarly, in React, there is a package named react-canvas-draw, which indirectly uses the canvas for drawing surface.
This package contains the different props and functions so that we can implement the feature very quickly. This is not compulsory to use this package but it will help you to implement such things without much complexity.
There are different operations supported as given below.
- Draw on canvas
- Clear canvas drawing
- Save data in a form of a picture or any significant object
- Undo the last drawing object
- Load the previously saved data
Prerequisites
Node 8.10.0 or a later version is required.
In order to work with this project, we need to create a new project using create-react-app, and if you don't have already installed the package, then execute the below npm command.
- npm install -g create-react-app
- // If using npm 5.1 or earlier
- create-react-app DemoApp
- // If using npm > 5.1
- npx create-react-app DemoApp
Then, we need to install the react-canvas-draw npm package by using the below command.
- npm install react-canvas-draw --save
- // Demo.js
- import React, { Component } from 'react';
- import CanvasDraw from "react-canvas-draw";
- export class Demo extends Component {
- render() {
- return (
- <div>
- <CanvasDraw
- ref={canvasDraw => (this.myCanvas = canvasDraw)}
- />
- <button
- onClick={() => {
- this.myCanvas.clear();
- }}
- >Clear
- </button>
- </div>
- );
- }
- }
Now, open the index.js file and use your Demo.js file in order to render the actual signature component.
- import React, { Component } from 'react';
- import { render } from 'react-dom';
- import './style.css';
- // Our re-usable canvas component
- import { Demo } from './Demo';
- class App extends Component {
- render() {
- return (
- <div>
- <h2>On-Screene Signature using React</h2><hr/>
- <Demo />
- </div>
- );
- }
- }
- render(<App />, document.getElementById('root'));
As you can see, I am able to draw the signature canvas using a mouse and at the same time, we can also remove our signature or any other drawing object.
Conclusion
This kind of functionality can be pretty easy to implement using HTML canvas where we can draw different objects. Also, we are able to draw different shapes, text, curves, and many more objects.

Join the conversation! Your thoughts help the community grow.