Create a react app and install react-canvas-draw dependency
npm install react-canvas-draw --save
We shall use a functional component to include the CanvasDraw component
This a basic setup where only few props are used. We now have a canvas component where the brush colour ,width has been set.The grid lines have been hidden.
For more props refer https://www.npmjs.com/package/react-canvas-draw
Undo and clear features can be included using reference to the component
Read more about it here Refs and the DOM
ref={(canvasDraw) => (this.modify = canvasDraw)}
Next let's accept user brush size and colour selections.We shall be building a palette from scratch.
You can also try react-colour-palette. A color picker component for React.
Since we are using react hooks in this app we shall begin by importing useState
hook from react
import {useState} from 'react'
Read more about hooks What is ReactHooks
First we shall set the initial state of the colour and width of the brush.
- canvas is initialized to the value given as an argument to the useState
- setBrush is the function used to modify the value of canvas
- brush is initialized to value 50
- setThick is used to modify the value of brush thickness
The modified ReactCanvas component
So we shall use input element of type color
Whenever the input element changes our brush colour variable canvas changes.As stated earlier we shall be making use of setBrush function to change the colour.
The thickness here shall vary between 2 and 50.
One can further add more features.
The complete code can be found here
Top comments (0)