July 6, 2022

Robotic Notes

All technology News

2D sketches with React and the Canvas API

6 min read

The Canvas API is a built-in HTML5 API for building and effectively drawing shapes to the screen. The following definition comes from the MDN web docs: The Canvas API allows drawing graphics via Javascript and the HTML <canvas> element. We can use it for animation, game graphics, data visualization, photo manipulation, and real-time video processing.

The Canvas API is primarily used to render 2D graphics to the screen. To render 3D graphics, the WebGL API should be used, but we’ll focus on 2D work here. The WebGL API can also render 2D graphics because it uses the canvas element.

This tutorial will cover the creation of the following:

  • A simple animation
  • A blank canvas where we can draw shapes and graphics

Properties and methods available in the Canvas API

Some properties and methods are available in the Canvas API, and this section will cover them. The difference between the properties and methods is that the properties set or return a particular color or pattern used in the drawings. In contrast, the methods create the designs used by the properties in the drawing. Some properties and methods include:

  • fillStyle: This property specifies the color or pattern used in the drawing.
  • font: This property specifies the font property for text content
  • strokeStyle: This property specifies the color used for the stroke.
  • createLinearGradient(): This method creates a linear gradient that can be used on the canvas.
  • rect(): This method creates a rectangle on the canvas.
  • fillRect(): This method draws a filled rectangle.
  • stroke(): This method draws the path you define.

You can read more about the methods and properties available to the canvas API here. The complete code for this article can be found here.

Creating a simple animation

Navigate to the folder of your choice and run the following command to create a new React application.

1yarn create react-app <NAME OF YOUR CHOICE>

You can clean up the file structure by deleting unnecessary files in the src folder. Create an Animation.jsx file, which will hold the code for the animation. Copy and paste the code below into the file.


2import React, { useRef } from 'react'


4const Animation =() => {


6 const canvasRef = useRef(null)

7 const draw = (ctx, frameCount) => {

8 ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);

9 ctx.fillStyle = 'blue';

10 ctx.beginPath();

11 ctx.arc(170, 50, 30 * Math.sin(frameCount * 0.05) ** 2, 0, 2 * Math.PI);

12 ctx.fill();

13 };


15 return <canvas style={{ width: '700px' }} ref={canvasRef} />;



18export default Animation

We returned a canvas element in the code block above and then imported the useRef hook from React. The useRef hook gives us a way to access the DOM elements without using the document.getElementById in React. Next, we created a draw function that takes two parameters: the ctx and the frameCount. Ctx is used to assess methods and properties in canvas API, while the frameCount counts the frames and provides a timer for animations in canvas. After that, the canvas was cleared, and the color used for the drawing was set. Then, we called the beginPath() method, which tells the canvas to start drawing. In the following line, we defined what we wanted to draw, which in this case is an arc. The arc() takes in five (5) mandatory parameters and one (1) optional parameter:

  • The x-coordinate
  • The y-coordinate
  • The radius of the circle
  • The starting angle in radians
  • The ending angle in radians

The optional parameter is the choice to specify if the drawing should be clockwise or counterclockwise. It is set to false by default which means clockwise.

1useEffect(() => {

2 const canvas = canvasRef.current;

3 const context = canvas.getContext('2d');

4 let frameCount = 0;

5 let animationFrameId;

6 const render = () => {

7 frameCount++;

8 draw(context, frameCount);

9 animationFrameId = window.requestAnimationFrame(render);

10 };

11 render();

12 return () => {

13 window.cancelAnimationFrame(animationFrameId);

14 };

15}, []);

In the code above block, we created a useEffect hook that will handle our application’s side effects because we won’t be able to run the animation for the application without it. Next, we define the canvas with the useRef and then get the canvas’s context which we set as 2D. We provided a render function that takes in the frameCount and the draw function, and we also provided it with the animationFrameIdwhich we set to the window.requestAnimationFrame() method. The window.requestAnimationFrame() method then calls the render function recursively

The window.requestAnimationFrame() method informs the browser that you want an animation performed. You can read more about the window.requestAnimationFrame() method here. Next, we provide a cleanup function to the useEffect hook. This cleanup function takes in the window.cancelAnimationFrame()which calls and cancels the animationFrameId.

Import the file into App.js, and with that, run yarn start to view the animation in the browser.


Building a blank canvas that accepts drawings

When building a canvas for accepting drawings or graphics, we have to take note of the mouse movements. We are interested in three (3) of those mouse movements. onMouseDown, onMouseUp, onMouseMove:

  • onMouseDown: The drawing starts when we hold the mouse down (Holding the mouse’s left key or double-tapping when using the trackpad on a laptop).
  • onMouseUp: The drawing stops whenever we stop holding the mouse down (when we stop holding the left key of the mouse or stop double-tapping when using the trackpad on a laptop).
  • onMouseMove: The drawing follows the movement of the mouse while the mouse is being held down.

We will write functions for handling those mouse movements. Create another file and name it Drawing.jsx. This file will hold the code that will allow us to draw on the canvas.

1import { useEffect, useRef, useState } from 'react';

2export default function Drawing() {

3 const [drawing, setDrawing] = useState(false);

4 const canvasRef = useRef(null);

5 const ctxRef = useRef(null);


7 return (

8 <>

9 <canvas

10 onMouseDown={startDraw}

11 onMouseUp={stopDraw}

12 onMouseMove={draw}

13 ref={canvasRef}

14 />

15 </>

16 );


In the code block above, we created a ref event for interacting with the canvas, and then we passed the ref to the canvas along with the three mouse movements. The second ref event is for storing the context so that we can use it when drawing on the canvas.

1const startDraw = ({ nativeEvent }) => {

2 const { offsetX, offsetY } = nativeEvent;

3 ctxRef.current.beginPath();

4 ctxRef.current.moveTo(offsetX, offsetY);

5 setDrawing(true);



8const stopDraw = () => {

9 ctxRef.current.closePath();

10 setDrawing(false);



13const draw = ({ nativeEvent }) => {

14 if (!drawing) return;

15 const { offsetX, offsetY } = nativeEvent;

16 ctxRef.current.lineTo(offsetX, offsetY);

17 ctxRef.current.stroke();



20const clear = () => {

21 ctxRef.current.clearRect(

22 0,

23 0,

24 canvasRef.current.width,

25 canvasRef.current.height

26 );


The code block above holds the functionalities that fire off the various mouse events. In the startDraw function, we pulled out the nativeEvent from the available browser events. Then we pulled out the offsetX and offsetY of the mouse event to know the mouse’s position at any point on the canvas. We then set the state of the drawing to true. In the stopDraw function, we called the closePath() method and then set the state of the drawing to true. An if check was set in the draw function, which returns immediately whenever there is no drawing on the canvas. A clear function was added to enable the clearing of the canvas when done with the drawing.



3useEffect(() => {

4 const canvas = canvasRef.current;


6 canvas.width = window.innerWidth * 2;

7 canvas.height = window.innerHeight * 2;

8 canvas.style.width = `${window.innerWidth}px`;

9 canvas.style.height = `${window.innerHeight}px`;


11 const ctx = canvas.getContext('2d');

12 ctx.scale(2, 2);

13 ctx.lineCap = 'round';

14 ctx.strokeStyle = 'blue';

15 ctx.lineWidth = 20;

16 ctxRef.current = ctx;

17}, []);



We imported the useEffect hook to manage the application’s side effects in the code block above. The context used is the 2D context, and we set the properties for the canvas. Import the code in the App.js so that it can be seen in the browser



This article taught about the Canvas API. The use of the Canvas API ranges from building signature pads for remote companies to data visualization and real-time video processing. The methods used in this article can be improved upon and used to develop complex animations and even game graphics.


Source link