Let’s take a look at how to get started with drawing shapes in a React app using the Konva.js canvas library/framework.

This is a short step-by-step guide to set up a React app and draw a simple shape in it. But first, let’s take a quick look at what we are gonna be working with:

React: React is a front-end framework developed and maintained by Facebook. It is highly popular in the frontend community (take a look at the statistics) and boosts with an enormous eco-systems consisting of thousands of packages.
The bare React-Framework is mostly being used to develop Single Page Applications, but there are other frameworks build on top of the React-Framework for developing other types of applications. An example of that would be the Next.js framework which is used to develop highly SEO-friendly Server-side rendered websites. In this short guide, we are gonna be using the bare React-Framework, but the steps should also be possible in most React deviations (like Next.js).

Konva: Konva.js is an object-oriented framework for drawing 2D shapes in the browser. It is built on top of the HTML5 canvas functionality and includes features like scaling, rotation, event handling, and animation.
In this guide, we will be using the react-konva package. This package ports most of the Konva objects to React components that we can simply include in our code.

Now that we have a rough understanding of what we will be using, we can finally start.

Setting Up the Project

To get started with this guide we need to create a new React app. For this, we will be npx and the handy create-react-app scaffolding.
This command set’s up most of what we need to start.

npx create-react-app react-konva-tutorial && cd react-konva-tutorial

After executing the command your folder should look somewhat like this:

create-react-app-folder-structure

Now we can proceed with installing Konva in our react app. Thanks to the previously mentioned react-konva this is actually quite easy:

npm install react-konva konva

With our dependencies installed we can start up the development server and write some code to display beautiful 2D shapes.

Starting the development server on Port 3000:

yarn start

Writing some Code

After executing create-react-app we are presented with a default App component, which looks something like this:

src/App.js

import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

We should clean it up a bit before proceeding. We are removing basically everything currently display and replace it with a simple text display.
So let’s just throw out the entire <header>-component and every import-statement that is now unused, and then add a <p>-tag.
This leaves us with this setup:

src/App.js

import './App.css';

function App() {
  return (
    <div className="App">
      <p> Hello There </p>
    </div>
  );
}

export default App;

Now we add our previously installed konva objects. At the top of the file we add a new import-statement.
This imports the 3 components: Stage, Layer, and Star into the current app component.

...
import { Stage, Layer, Star } from 'react-konva'
...

Stage: The Stage is the start of the entire Konva architecture. It is the container for one or multiple layers and needs to be present whenever we want to draw something.

Layer: The layer is the first component beneath the Stage. A layer has two renderers for the canvas: one for rendering the scene and another for detecting events.

Star: This is the shape we will be drawing in our application. This react component has properties we can later set to determine how the shape will be drawn. Some examples we will be using are number of points, radius (inner and outer), and color.

Konva.js supports much more than the simple structure we are aiming for. It is easily possible to draw complex shapes, draw over multiple layers, or group objects.

Check out the official Konva.js documentation for more information on this.

We can now proceed with displaying a simple shape in our application. For this we will be adding the previously imported components in the following order:

Stage ---> Layer ----> Star

Before we can see our shape, we need to configure the Stage and Star components.
The stage needs to be initialized with a width and height, as everything below it is rendered dynamically and can’t be used to compute the needed height and width of its parent.
In this example, we are setting the dimensions to the ones of our window.

...
<Stage width={window.innerWidth} height={window.innerHeight}>
...

The star component needs a few more properties to be visible. The first needed property is the position of the star component.
This is expressed as x and y coordinates and we will be setting them to half of our width and height so that the star is displayed right in the center.

x={window.innerWidth / 2}
y={window.innerHeight / 2}

Next up we need to configure the actual shape of the star. Therefore we set the number of points (or jags), as well as the inner and outer radius.
The radiuses determine where the jags of the star start and end.

numPoints={5}
innerRadius={20}
outerRadius={40}

We now have a star, but we can’t see it yet. To be able to see it, we need to give it a color different from the default white of the background.
I chose green as a color, but feel free to choose whatever you like.

To sum it all up, this leaves us with the following snippet of code within our App component:

  ...
  return (
    <div className="App">
      <Stage width={window.innerWidth} height={window.innerHeight}>
        <Layer>
          <Star 
            x={window.innerWidth / 2}
            y={window.innerHeight / 2}
            numPoints={5}
            innerRadius={20}
            outerRadius={40}
            fill="#0f0"
            opacity={0.8}
          />
        </Layer>
      </Stage>
    </div>
  );
  ...

And if we now switch over to our browser and go to http://localhost:3000 we can see our star.

I hope you enjoyed this quick read and that it helped you to get started with Konva and React.
I am thinking about extending this guide to include topics like:

  • Transformation (Dragging, Rotating and Scaling Shapes)
  • Implementing a selection box
  • Group Transformations
  • Implementing a menu to dynamically add and remove shapes

So leave me a comment if you are interested in of those topics and see you next time!