React Konva

React + Canvas = Love. JavaScript library for drawing complex canvas graphi...

README

React Konva

Build Status Greenkeeper badge

ReactKonva Logo

React Konva is a JavaScript library for drawing complex canvas graphics using

It provides declarative and reactive bindings to the


An attempt to make React work with the HTML5
canvas library. The goal is to have similar declarative markup as normal React
and to have similar data-flow model.

At the current moment, react-konva is not supported in React Native environment.

Currently you can use all Konva components as React components and all Konva
events are supported on them in same way as normal browser events are supported.

Installation


  1. ``` sh
  2. npm install react-konva konva --save
  3. ```


Example


  1. ``` js
  2. import React, { Component } from 'react';
  3. import { render } from 'react-dom';
  4. import { Stage, Layer, Rect, Text } from 'react-konva';
  5. import Konva from 'konva';

  6. class ColoredRect extends React.Component {
  7.   state = {
  8.     color: 'green',
  9.   };
  10.   handleClick = () => {
  11.     this.setState({
  12.       color: Konva.Util.getRandomColor(),
  13.     });
  14.   };
  15.   render() {
  16.     return (
  17.       <Rect
  18.         x={20}
  19.         y={20}
  20.         width={50}
  21.         height={50}
  22.         fill={this.state.color}
  23.         shadowBlur={5}
  24.         onClick={this.handleClick}
  25.       />
  26.     );
  27.   }
  28. }

  29. class App extends Component {
  30.   render() {
  31.     // Stage is a div container
  32.     // Layer is actual canvas element (so you may have several canvases in the stage)
  33.     // And then we have canvas shapes inside the Layer
  34.     return (
  35.       <Stage width={window.innerWidth} height={window.innerHeight}>
  36.         <Layer>
  37.           <Text text="Try click on rect" />
  38.           <ColoredRect />
  39.         </Layer>
  40.       </Stage>
  41.     );
  42.   }
  43. }

  44. render(<App />, document.getElementById('root'));
  45. ```

To get more info about Konva you can read

Actually you don't need to learn react-konva. Just learn Konva framework, you will understand how to use react-konva

Core API


react-konva supports all shapes, that Konva supports with the same names, and also it supports all the same events like click, touchmove, dragend, etc with "on" prefix like onClick, onTouchMove, onDragEnd.

Getting reference to Konva objects


To get reference of Konva instance of a node you can use ref property.

  1. ``` js
  2. class MyShape extends React.Component {
  3.   componentDidMount() {
  4.     // log Konva.Circle instance
  5.     console.log(this.circle);
  6.   }
  7.   render() {
  8.     return (
  9.       <Circle ref={(ref) => (this.circle = ref)} radius={50} fill="black" />
  10.     );
  11.   }
  12. }
  13. ```

Strict mode


By default react-konva works in "non-strict" mode. If you changed a property manually (or by user action like drag&drop) properties of the node will be not matched with properties from render(). react-konva updates ONLY properties changed in render().

In strict mode react-konva will update all properties of the nodes to the values that you provided in render() function, no matter changed they or not.

You should decide what mode is better in your actual use case.

To enable strict mode globally you can do this:

  1. ``` js
  2. import { useStrictMode } from 'react-konva';

  3. useStrictMode(true);
  4. ```

Or you can enable it only for some components:

  1. ``` js
  2. <Rect width={50} height={50} fill="black" _useStrictMode />
  3. ```

Take a look into this example:

  1. ``` js
  2. import { Circle } from 'react-konva';
  3. import Konva from 'konva';

  4. const Shape = () => {
  5.   const [color, setColor] = React.useState();

  6.   return (
  7.     <Circle
  8.       x={0}
  9.       y={0}
  10.       draggable
  11.       radius={50}
  12.       fill={color}
  13.       onDragEnd={() => {
  14.         setColor(Konva.Util.getRandomColor());
  15.       }}
  16.     />
  17.   );
  18. };
  19. ```

The circle is draggable and it changes its color on dragend event. In strict mode position of the node will be reset back to {x: 0, y: 0} (as we defined in render). But in non-strict mode the circle will keep its position, because x and y are not changed in render.

Minimal bundle


By default react-konva imports full Konva version. With all the shapes and all filters. To minimize bundle size you can use minimal core version of react-konva:

  1. ``` js
  2. // load minimal version of 'react-konva`
  3. import { Stage, Layer, Rect } from 'react-konva/lib/ReactKonvaCore';

  4. // minimal version has NO support for core shapes and filters
  5. // if you want import a shape into Konva namespace you can just do this:
  6. import 'konva/lib/shapes/Rect';
  7. ```


Usage with React Context


Note: this section may be not relevant, because this issue was fixed in react-konva@18.2.2. So context should work by default.

Due to a known issue with React, Contexts are not accessible by children of the react-konvaStage component. If you need to subscribe to a context from within the Stage, you need to "bridge" the context by creating a Provider as a child of the Stage. For more info, see this discussion and this react-redux demo. Here is an example of bridging the context (live demo):

  1. ``` js
  2. import React, { Component } from 'react';
  3. import Konva from 'konva';
  4. import { render } from 'react-dom';
  5. import { Stage, Layer, Rect } from 'react-konva';

  6. const ThemeContext = React.createContext('red');

  7. const ThemedRect = () => {
  8.   const value = React.useContext(ThemeContext);
  9.   return (
  10.     <Rect x={20} y={50} width={100} height={100} fill={value} shadowBlur={10} />
  11.   );
  12. };

  13. const Canvas = () => {
  14.   return (
  15.     <ThemeContext.Consumer>
  16.       {(value) => (
  17.         <Stage width={window.innerWidth} height={window.innerHeight}>
  18.           <ThemeContext.Provider value={value}>
  19.             <Layer>
  20.               <ThemedRect />
  21.             </Layer>
  22.           </ThemeContext.Provider>
  23.         </Stage>
  24.       )}
  25.     </ThemeContext.Consumer>
  26.   );
  27. };

  28. class App extends Component {
  29.   render() {
  30.     return (
  31.       <ThemeContext.Provider value="blue">
  32.         <Canvas />
  33.       </ThemeContext.Provider>
  34.     );
  35.   }
  36. }
  37. ```

Comparisons


react-konva vs react-canvas


react-canvas is a completely
different react plugin. It allows you to draw DOM-like objects (images, texts)
on canvas element in very performant way. It is NOT about drawing graphics, but
react-konva is exactly for drawing complex graphics on `` element from
React.

react-konva vs react-art


react-art allows you to draw graphics on
a page. It also supports SVG for output. But it has no support of events of
shapes.

react-konva vs vanilla canvas


Vanilla canvas is faster because when you use react-konva you have two layers of abstractions. Konva framework is on top of canvas and React is on top of Konva.
Depending on the use case this approach can be slow.
The purpose of react-konva is to reduce the complexity of the application and use well-known declarative way for drawing on canvas.


Note: you can find a lot of demos and examples of using Konva there:
http://konvajs.github.io/. Really, just go there and take a look what Konva can do for you. You will be able to do the same withreact-konva too.