DEV Community

Ankur Sheel
Ankur Sheel

Posted on • Updated on • Originally published at ankursheel.com

React Component to draw on a page using Hooks and Typescript

Recently, How to Create the Drawing Interaction on DEV's Offline Page by Ali Spittel showed up in my feed and it looked quite cool. This got me wondering if I could create the same thing as a React component using Hooks and typescript. Well, the fact that I am writing this post means I was able to recreate it. So let's see how I did it.

If you are interested in the final product, you can check out the Github repository. There is also a sandbox you can play with at the end of this post.

This post assumes you already know how to work with TypeScript and hooks.


Creating the Component

The first thing we need to do is to create a Canvas component. The canvas needs to take up some space which we will want any parent component to be able to override so we will add width and height as props. But, We want to add a sensible default so that We don't have to add these props every time we want to use this component. We will add some defaultProps to set these values to window.innerWidth and window.innerHeight respectively.

import React from 'react';

interface CanvasProps {
    width: number;
    height: number;
}

const Canvas = ({ width, height }: CanvasProps) => {
     return <canvas height={height} width={width} />;
};

Canvas.defaultProps = {
    width: window.innerWidth,
    height: window.innerHeight,
};

export default Canvas;

Lets Draw

Since we need to modify the canvas element, we will need to add a ref to it. We can do this by using useRef hook and modifying our canvas element to set the ref.

const canvasRef = useRef<HTMLCanvasElement>(null);
return <canvas ref={canvasRef} height={height} width={width} />;

Set state

We need to keep track of some variables

  • the mouse position.
  • whether we are painting or not.

We can do this by adding the useState hook.
We will also create a Coordinate type to help with keeping track of mouse positions.

type Coordinate = {
    x: number;
    y: number;
};

const Canvas = ({ width, height }: CanvasProps) => {
const [isPainting, setIsPainting] = useState(false);
const [mousePosition, setMousePosition] = useState<Coordinate | undefined>(undefined);
// ... other stuff here

Start drawing when the mouse is pressed.

We will add the event listener in the useEffect hook. If we have a valid reference to the canvas, we add an event listener to the mouseDown event. We also remove the event listener when we unmount.

 useEffect(() => {
        if (!canvasRef.current) {
            return;
        }
        const canvas: HTMLCanvasElement = canvasRef.current;
        canvas.addEventListener('mousedown', startPaint);
        return () => {
            canvas.removeEventListener('mousedown', startPaint);
        };
    }, [startPaint]);

startPaint needs to get the current coordinates of the mouse and set isPainting to true. We will also wrap it in a useCallback hook so that we can use it inside the useEffect hook.

 const startPaint = useCallback((event: MouseEvent) => {
        const coordinates = getCoordinates(event);
        if (coordinates) {
            setIsPainting(true);
            setMousePosition(coordinates);
        }
    }, []);

// ...other stuff here

const getCoordinates = (event: MouseEvent): Coordinate | undefined => {
    if (!canvasRef.current) {
        return;
    }

    const canvas: HTMLCanvasElement = canvasRef.current;
    return {event.pageX - canvas.offsetLeft, event.pageY - canvas.offsetTop};
};

Draw the line on mouse move

Similar to the mouseDown event listener we will use the useEffect hook to add the mousemove event.

useEffect(() => {
        if (!canvasRef.current) {
            return;
        }
        const canvas: HTMLCanvasElement = canvasRef.current;
        canvas.addEventListener('mousemove', paint);
        return () => {
            canvas.removeEventListener('mousemove', paint);
        };
    }, [paint]);

paint needs to

  • Check if we are painting.
  • Get the new mouse coordinates.
  • Draw a line from the old coordinates to the new one by getting the rendering context from the canvas.
  • Update the old coordinates.
const paint = useCallback(
        (event: MouseEvent) => {
            if (isPainting) {
                const newMousePosition = getCoordinates(event);
                if (mousePosition && newMousePosition) {
                    drawLine(mousePosition, newMousePosition);
                    setMousePosition(newMousePosition);
                }
            }
        },
        [isPainting, mousePosition]
    );

// ...other stuff here

const drawLine = (originalMousePosition: Coordinate, newMousePosition: Coordinate) => {
        if (!canvasRef.current) {
            return;
        }
        const canvas: HTMLCanvasElement = canvasRef.current;
        const context = canvas.getContext('2d');
        if (context) {
            context.strokeStyle = 'red';
            context.lineJoin = 'round';
            context.lineWidth = 5;

            context.beginPath();
            context.moveTo(originalMousePosition.x, originalMousePosition.y);
            context.lineTo(newMousePosition.x, newMousePosition.y);
            context.closePath();

            context.stroke();
        }
    };

Stop drawing on mouse release

We want to stop drawing when either the user releases the mouse or they move the mouse out of the canvas area

useEffect(() => {
        if (!canvasRef.current) {
            return;
        }
        const canvas: HTMLCanvasElement = canvasRef.current;
        canvas.addEventListener('mouseup', exitPaint);
        canvas.addEventListener('mouseleave', exitPaint);
        return () => {
            canvas.removeEventListener('mouseup', exitPaint);
            canvas.removeEventListener('mouseleave', exitPaint);
        };
    }, [exitPaint]);

In exitPaint we just set the isPainting to false

const exitPaint = useCallback(() => {
        setIsPainting(false);
    }, []);

And, we have a React component that we can reuse. You can see the final code in either the Github repository. Play with the sandbox below.


Sandbox


Let me if you have any questions in the comments :)


Updates:

  • Updated 24 Sep 2019: Fixed incorrect code in getCoordinates. Thanks, Jibin for pointing it out.

Top comments (2)

Collapse
 
jibin23 profile image
Jibin Joseph

Please correct the getCoordinates function to return an object with keys x and y, as it is in your codesandbox. In the blogpost it returns an array.

const getCoordinates = (event: MouseEvent): Coordinate | undefined => {
    if (!canvasRef.current) {
        return;
    }

    const canvas: HTMLCanvasElement = canvasRef.current;
    return [event.pageX - canvas.offsetLeft, event.pageY - canvas.offsetTop];
};

Great post!

Collapse
 
ankursheel profile image
Ankur Sheel

Thanks for pointing out the mistake. I have fixed it in the post.
Glad you liked it :)