React Canvas

Learn via video courses
Topics Covered

Overview

React Canvas is a rectangular area on our web pages that helps to draw graphics and animations. The React canvas element can be used in React applications to draw animations.

Method - 1: "react-canvas-draw"

React canvas is a powerful and straightforward tool for creating components for React for canvas drawing.

Installation

The first step before using any dependency is to download the required dependencies. You can download the react-canvas-draw dependency using either of the two popular javascript package managers:

Install via NPM

Install via Yarn

Usage

Once we have installed the react-canvas dependency, let us see how we can create a simple canvas component using "react-canvas-draw".

Functions

Let us see some functions that we can call when we have a reference to the component:

  • loadSaveData(saveData: String, immediate: Boolean):
    This method loads a saved drawing data back to the canvas. The optional boolean flag loads data immediately instead of drawing it live.
  • getSaveData():
    This method is used to get the canvas drawing data in a stringified object for programmers to save and use later.
  • getDataURL(fileType, useBgImage, backgroundColor):
    The method will export the canvas data to a data URL that can subsequently be used to share and manipulate the image file.
  • clear():
    As the name suggests, the function clears the react drawing canvas and resets the view.
  • eraseAll():
    The function like clear() clears the drawn line, but the drawing data is retained, and calling the undo() function can restore the erased data.
  • resetView():
    The function resets the react drawing canvas view back to the default.
  • undo():
    The function removes the latest changes made on the drawing, which includes everything since the last MouseDown event.

Props

The CanvasDraw component has a list of default props; you can play with these props to customize the CavasDraw component as needed. Here is the list of default components

Method: Using Canvas API

Canvas Component

The first thing we need is a react drawing canvas component to draw inside. Let us create a fundamental canvas component.

Here, we have created a React Canvas component wrapping a canvas element. To draw, we need to get the context object. In react to do this, we need to get the ref prop.

Canvas Context

To get the context of the react drawing canvas, we need to create a ref and give the ref to the element:

Now that we have created a ref for our canvas element, we can access the canvas element using the canvasRef, and we can start drawing.

Explanation:

But this code still does not work as the component is not mounted when we tried getting the canvas through the ref; hence, the value we get is the initial value we gave to it, i.e., null. We must wait for the component to mount before accessing its context.

The useEffect hook allows us to achieve this condition. Using the hook, we can call the function just after the component is mounted the component is updated, or change some variable. Here we are interested in the first case when the component is mounted. We want to get the component in javascript context, as soon as the component mounts. We pass an empty array as the useEffect parameter which allows us to use the useEffect method as componentDidMount, as shown in the code snippet below:

Now we can draw on our react canvas drawing.

Draw

So far, we can create a black rectangle in our canvas, but we want to make it more dynamic. Let us see how we can do it.

Explanation:

Notice how we change the array or the second argument in the useEffect function. Now it is not empty; everything we put in the array as dependency is watched by the useEffect. When the values in the dependency array change, the function will be called with the updated values. Every time we change the draw function, the useEffect will be called again. Still, we have a static drawing on our react canvas. Let us make some changes to create an animation.

Explanation:

Let us see what is happening in our function here.

  • All the steps repeated in the animation are wrapped in a function render(), which is called recursively by the function requestAnimationFrame.
  • The variable frameCount is used to control the animation time, we can change the animation speed by changing the rate at which we increase/decrease the function.
  • The draw function takes the frameCount as a function parameter and draws the circle. The argument frameCount controls the radius of the circle.
  • The function returned after the useEffect callback function is called when the component unmounts.

Canvas Hook in React

The only thing we need to give to our logic is the callback draw function, and we need to pass only the canvas reference to our component. Our canvas component should look like this:

The callback function draw is given to the hook, and the ref for the react canvas drawing element is returned. Now we copy the complete logic to our useCanvas hook and make it a function that receives the draw callback function and returns the canvas reference.

Some Extra Features of the Canvas

Let us see a few additional features and functionalities we can achieve using the react canvas.

Setup Canvas

We should make our canvas prop flexible enough such that if we wish to use any configurations or context other than 2d, our implementation should be able to use it.

We can modify our current hook implementation to make it accept new arguments.

Our hook implementation will change to:

Explanation:

Here, we ensured that our hook falls back to the initial implementation and configurations providing more usability.

Resizing Function

We currently have a canvas of fixed dimensions and do not have control over our canvas size.

Let us see the following code that will help us to track the canvas size and resize it.

From the code snippet mentioned above, we can set the size of our canvas using only the CSS.

The function can be called inside the draw function or before calling the draw function.

High-pixel-density Devices

Our canvas drawing might look blurry in modern high-pixel-density devices such as smartphones.

To prevent this from happening, we must define our canvas size based on the device pixel ratio.

Explanation:

Here, we are taking into account the device pixel ratio to resize the canvas preventing situations where our draw might appear blurry.

Pre-draw and Post-draw

There are some actions in our animation that we need to perform for every animation. It is better to extract such steps into separate functions that execute before and after each draw: predraw and postdraw.

These separations will help us write faster animations without the need to repeat common steps for different animations.

Conclusion

  • Canvas is a rectangular area on our web pages that helps to draw graphics and animations.
  • React canvas is a powerful and straightforward tool for creating components for React for canvas drawing.
  • The CanvasDraw component has a specific list of default props. You can play with these props to customize the CavasDraw component as needed.
  • Another method to use canvas in React is to use the canvas HTML element and use its reference to draw on the canvas.
  • With a canvas in React we can also draw to handle High-pixel-density devices and create functions like Pre-draw and post-draw for faster animation.