What is react-konva?
react-konva is a React wrapper for the Konva framework, which is a 2D canvas library for creating complex graphics on the web. It allows developers to use React components to draw shapes, images, and text on the canvas, making it easier to integrate with React applications.
What are react-konva's main functionalities?
Drawing Shapes
This feature allows you to draw basic shapes like rectangles and circles on the canvas. The code sample demonstrates how to create a red rectangle and a green circle using React components.
```jsx
import React from 'react';
import { Stage, Layer, Rect, Circle } from 'react-konva';
const DrawingShapes = () => (
<Stage width={window.innerWidth} height={window.innerHeight}>
<Layer>
<Rect x={20} y={20} width={100} height={100} fill='red' />
<Circle x={200} y={200} radius={50} fill='green' />
</Layer>
</Stage>
);
export default DrawingShapes;
```
Handling Events
This feature allows you to handle user interactions like clicks and drags. The code sample shows how to display an alert when a blue rectangle is clicked.
```jsx
import React from 'react';
import { Stage, Layer, Rect } from 'react-konva';
const HandlingEvents = () => {
const handleClick = () => {
alert('Rectangle clicked!');
};
return (
<Stage width={window.innerWidth} height={window.innerHeight}>
<Layer>
<Rect x={20} y={20} width={100} height={100} fill='blue' onClick={handleClick} />
</Layer>
</Stage>
);
};
export default HandlingEvents;
```
Animating Shapes
This feature allows you to animate shapes on the canvas. The code sample demonstrates how to animate a purple rectangle moving horizontally across the screen.
```jsx
import React, { useRef, useEffect } from 'react';
import { Stage, Layer, Rect } from 'react-konva';
const AnimatingShapes = () => {
const rectRef = useRef(null);
useEffect(() => {
const anim = new Konva.Animation((frame) => {
const rect = rectRef.current;
rect.x((rect.x() + frame.timeDiff * 0.1) % window.innerWidth);
}, rectRef.current.getLayer());
anim.start();
return () => anim.stop();
}, []);
return (
<Stage width={window.innerWidth} height={window.innerHeight}>
<Layer>
<Rect ref={rectRef} x={20} y={20} width={100} height={100} fill='purple' />
</Layer>
</Stage>
);
};
export default AnimatingShapes;
```
Other packages similar to react-konva
react-three-fiber
react-three-fiber is a React renderer for Three.js, a popular 3D graphics library. While react-konva focuses on 2D canvas graphics, react-three-fiber is used for creating 3D scenes and objects. It provides a similar React-based approach to managing graphics but in a 3D context.
react-canvas
react-canvas is another library for drawing graphics using React components, but it is more focused on performance and rendering large lists of items efficiently. It is less feature-rich in terms of drawing complex shapes and animations compared to react-konva.
react-svg
react-svg is a library for integrating SVG graphics into React applications. While it also deals with vector graphics, it uses SVG instead of the HTML5 canvas element. It is more suitable for static or less complex graphics compared to the dynamic and interactive capabilities of react-konva.
React Konva
React Konva is a JavaScript library for drawing complex canvas graphics using
React.
It provides declarative and reactive bindings to the
Konva Framework.
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
npm install react-konva konva --save
Example
import React, { Component } from 'react';
import { render } from 'react-dom';
import { Stage, Layer, Rect, Text } from 'react-konva';
import Konva from 'konva';
class ColoredRect extends React.Component {
state = {
color: 'green'
};
handleClick = () => {
this.setState({
color: Konva.Util.getRandomColor()
});
};
render() {
return (
<Rect
x={20}
y={20}
width={50}
height={50}
fill={this.state.color}
shadowBlur={5}
onClick={this.handleClick}
/>
);
}
}
class App extends Component {
render() {
return (
<Stage width={window.innerWidth} height={window.innerHeight}>
<Layer>
<Text text="Try click on rect" />
<ColoredRect />
</Layer>
</Stage>
);
}
}
render(<App />, document.getElementById('root'));
To get more info about Konva
you can read
Konva Overview.
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.
class MyShape extends React.Component {
componentDidMount() {
console.log(this.circle);
}
render() {
return <Circle ref={ref => (this.circle = ref)} radius={50} fill="black" />;
}
}
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:
import { useStrictMode } from 'react-konva';
useStrictMode(true);
Or you can enable it only for some components:
<Rect width={50} height={50} fill="black" _useStrictMode />
Take a look into this example:
import { Circle } from 'react-konva';
import Konva from 'konva';
const Shape = () => {
const [color, setColor] = React.useState();
return (
<Circle
x={0}
y={0}
draggable
radius={50}
fill={color}
onDragEnd={() => {
setColor(Konva.Util.getRandomColor());
}}
/>
);
};
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
:
import { Stage, Layer, Rect } from "react-konva/lib/ReactKonvaCore";
import "konva/lib/shapes/Rect";
Demo: https://codesandbox.io/s/6l97wny44z
Usage with React Context
Due to a known issue with React, Contexts are not accessible by children of the react-konva Stage
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):
import React, { Component } from "react";
import Konva from "konva";
import { render } from "react-dom";
import { Stage, Layer, Rect } from "react-konva";
const ThemeContext = React.createContext("red");
const ThemedRect = () => {
const value = React.useContext(ThemeContext);
return (
<Rect x={20} y={50} width={100} height={100} fill={value} shadowBlur={10} />
);
};
const Canvas = () => {
return (
<ThemeContext.Consumer>
{value => (
<Stage width={window.innerWidth} height={window.innerHeight}>
<ThemeContext.Provider value={value}>
<Layer>
<ThemedRect />
</Layer>
</ThemeContext.Provider>
</Stage>
)}
</ThemeContext.Consumer>
);
};
class App extends Component {
render() {
return (
<ThemeContext.Provider value="blue">
<Canvas />
</ThemeContext.Provider>
);
}
}
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 <canvas>
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 with react-konva
too.