konvajs / react-konva Goto Github PK
View Code? Open in Web Editor NEWReact + Canvas = Love. JavaScript library for drawing complex canvas graphics using React.
Home Page: https://konvajs.github.io/docs/react/
License: MIT License
React + Canvas = Love. JavaScript library for drawing complex canvas graphics using React.
Home Page: https://konvajs.github.io/docs/react/
License: MIT License
In the source code, event will be transform to lowercase, but stage event like contentMousedown needs uppercase. So I think better check if there's the keyword content before transforming it.
I get this error when mounting a shape and layer:
ReferenceError: Image is not defined
at Object.applyNodeProps (client/node_modules/react-konva/src/react-konva.js:224:28)
at Object.componentDidMount (client/node_modules/react-konva/src/react-konva.js:268:10)
at client/node_modules/react-dom/lib/ReactCompositeComponent.js:265:25
I even get it when running your test:
import React from 'react';
import { expect } from 'chai';
import { shallow, mount, render } from 'enzyme';
import {Stage, Layer, Rect} from '../src/react-konva';
import './mocking';
import Konva from 'konva';
import sinon from 'sinon';
describe("Test references", function() {
let instance;
class App extends React.Component {
render() {
return (
<Stage ref="stage" width={300} height={300}>
<Layer ref="layer">
</Layer>
</Stage>
);
}
}
beforeEach(() => {
const wrapper = mount(<App/>);
instance = wrapper.instance();
});
it("can get stage instance", function() {
const stageRef = instance.refs.stage;
expect(stageRef.getStage() instanceof Konva.Stage).to.equal(true);
});
it("check initial props set", function() {
const stage = instance.refs.stage.getStage();
expect(stage.width()).to.equal(300);
expect(stage.height()).to.equal(300);
});
it("can get layer instance", function() {
expect(instance.refs.layer instanceof Konva.Layer).to.equal(true);
});
});
Seems like a dependency issue, but I've got canvas
, jsdom
, and konva
installed.
I'm using mocha (but not mocha-phantomjs).
Not seeing anything online about it. Certainly not using any Image
components. Any ideas?
Do you plan to support the Konva.Animation?
If want to move rect, have to use the raf?
I'm planning on rewriting some code in react-konva, and I noticed that it wasn't drawing anyting.
I tried the demo, and it seems that the problem might be a delayed call to ReactDOM.render.
No canvas appears in the dom tree.
I added this to the demo:
setTimeout(function(){
ReactDOM.render(<App/>, document.getElementById('container'));
}, 1000)
<Rect zIndex={100} id="upper-rect" draggable="true" x={2} y={0} width={100} height={1000} fill={'#555555'} onClick={null}/>
<Rect zIndex={5} id="lower-rect" draggable="true" x={20} y={20} width={50} height={50} fill={'#777777'} onClick={null}/>
Don't works.
Hi - I have following React code:
<Stage onMouseDown={e => console.log(e)}> <Layer> <Rect onClick={e => console.log(e)} /> </Layer> </Stage>
I added a logging statement where react-konva does the node.on(eventName, handler), and seeing the stage event handler is being registered successfully. However, when I run the code, console logging only happens when I click on the Rect. Clicking on the Stage yields nothing. Am I missing something here?
Thanks for any help!
Hello.
I found out react-konva
always imports whole konva
package. It highly increases webpack bundle size.
Is it possible to require only necessary sources?
Thank you.
Hi!
I am using this simple function to create image objects
function imageFactory(x) {
const rv = document.createElement('img')
rv.src = x
return rv
}
I use it in ES6 JSX like this:
render() {
return (
<Stage width={707} height={267}>
<Layer>
<Image x={0} y={0} width={707} height={267} image={imageFactory(require('./images/image.jpg'))}/>
// ...
However, on a page with two such elements, sometimes one shows up, sometimes both, sometimes none.
Should I be using some other approach?
The require
statement is from webpack and just returns a relative string to the image, so it should be all fine.
Hello there,
After installing react-konva I tried to run my application. However, I got this message:
Unable to resolve some modules:
"canvas" in /Users///node_modules/konva/konva.js
(web.browser)
"jsdom" in /Users///node_modules/konva/konva.js
(web.browser)
It can still render the shapes normally. I'm wondering how I can ommit this warning??
Thanks
Is there a reason for not having Transform.point() in the typings file?
Hi,
I'm having trouble generating polygons properly. I tried integrating the example polygon from the Konva Doc and the rectangle konva-react demo.
Here's what I'm seeing: http://jsbin.com/vuxatexovi/edit?js,output
Any help would be much appreciated! Thanks!
Not all source files are included when the package is installed. More precisely, the only relevant source file, react-konva.js
, haha. Is this a problem with your package or with npm?
This happens sometimes (frequently, but not always), when the mouse leaves the canvas area.
Uncaught TypeError: Cannot read property 'call' of null
at Konva.Image._fire (konva.js:4184)
at Konva.Image._fireAndBubble (konva.js:4158)
at Konva.Stage._mousemove (konva.js:9214)
at HTMLDivElement.<anonymous> (konva.js:8807)
The relevant lines in Konva.Image._fire are:
if (events) {
for(i = 0; i < events.length; i++) {
events[i].handler.call(this, evt);
}
}
events[i].handler
is null.
The event is a mouseenter event. I believe it is registered in the Stage.componentWillMount method.
I ran into a problem trying to recreate this example from the konva website.
http://konvajs.github.io/docs/shapes/Text.html
The nesting of the text inside of the rectangle doesn't work. However, if I render them separately the text shows up fine.
http://jsbin.com/kukibo/edit?js,output
Hi,
I'm trying to scale the whole canvas in a way that the internal elements will be scaled as well.
Is it something provided out-of-the-box with react-konva?
I found the Transform class in Konva but I don't find a way to make it work with React.
I thought this would work:
<Stage>
<Transform>
</Transform>
</Stage>
But React complains because Transform isn't exposed by react-konva.
Hey there!
I'm creating a mobile-focused project with React. I want the UI animations and touch gestures to be very performant, and as near to native-like as possible, so I'm looking at implementing some sort of canvas based renderer for the app.
I've boiled down to two choices, react-canvas and react-konva.
The benefit of react-canvas to me seems to be that it's more targeted towards creating interfaces, wheras konva seems less so. That being said, Konva is still actively maintained and developed, while Flipboard seems to have let react-canvas fall behind.
So I wanted to ask, how practical is it to use react-konva for building complete app UI, comparable to react-canvas?
Thanks for any input. :)
I'm trying to write some tests with Jest Snapshots. However, when I try to render a component with a Konva stage in it, i get an error. Here's the code in question and the resulting error after running Jest.
import React from 'react'
import renderer from 'react-test-renderer'
import Home from './'
describe('<Home />', () => {
it('renders initial UI', () => {
const tree = renderer.create(<Home />).toJSON()
expect(tree).MatchSnapshot()
})
})
<Home />
contains a Stage
component.
Here's the resulting error:
TypeError: Cannot read property 'getPooled' of null
at Object.componentDidMount (node_modules/react-konva/src/react-konva.js:270:61)
at node_modules/react-test-renderer/lib/ReactCompositeComponent.js:265:25
at measureLifeCyclePerf (node_modules/react-test-renderer/lib/ReactCompositeComponent.js:75:12)
at node_modules/react-test-renderer/lib/ReactCompositeComponent.js:264:11
at CallbackQueue.notifyAll (node_modules/react-test-renderer/lib/CallbackQueue.js:76:22)
at ReactTestReconcileTransaction.close (node_modules/react-test-renderer/lib/ReactTestReconcileTransaction.js:36:26)
at ReactTestReconcileTransaction.closeAll (node_modules/react-test-renderer/lib/Transaction.js:206:25)
at ReactTestReconcileTransaction.perform (node_modules/react-test-renderer/lib/Transaction.js:153:16)
at batchedMountComponentIntoNode (node_modules/react-test-renderer/lib/ReactTestMount.js:69:27)
at ReactDefaultBatchingStrategyTransaction.perform (node_modules/react-test-renderer/lib/Transaction.js:140:20)
at Object.batchedUpdates (node_modules/react-test-renderer/lib/ReactDefaultBatchingStrategy.js:62:26)
at Object.batchedUpdates (node_modules/react-test-renderer/lib/ReactUpdates.js:97:27)
at Object.render [as create] (node_modules/react-test-renderer/lib/ReactTestMount.js:125:18)
at Object.<anonymous> (src/scenes/Home/Home.test.js:7:44)
at process._tickCallback (internal/process/next_tick.js:103:7)
Getting this error when I try to apply a filter to an image after upload.
konva.js:1115 Konva error: Unable to apply filter. Failed to execute 'getImageData' on 'CanvasRenderingContext2D': Out of memory at ImageData creation
As you can tell i'm doing a lot of things here but between the font loading and image loading i'm not sure when to cache my image.
const globalKonva = window.Konva;
class WodCanvas extends Component {
constructor(props){
super(props);
this.state = {
image: this.props.img,
font: 'Montserrat:700'
}
}
componentwillmount(){}
componentDidUpdate(prevProps, prevState){
if(prevProps.img !== this.props.img){
this.updateCanvas();
}
}
componentDidMount() {
this.updateCanvas();
}
updateCanvas(){
const image = new window.Image();
const imgSrc = this.props.img;
WebFont.load({
google: {
families: ['Rubik One','Roboto','Montserrat:700']
},
active: function() {
image.src = imgSrc;
}
});
image.onload = () => {
this.wodimage.cache();
this.setState({
image: image,
font: 'Montserrat'
},()=>{
this.image.cache();
});
}
}
render(){
return (
<Stage width={500} height={500} className="wodcanvas" >
<Layer >
<Rect filters={[globalKonva.Filters.Noise]} noise={1} x={0} y={0} width={500} height={500} fill="red" ref={(node) => { this.rect = node;}} />
<Image filters={[globalKonva.Filters.Blur]} blurRadius={5} opacity="0.25" width="500" height="500" image={this.state.image} ref={(node) => { this.image = node;}} />
<Text x="20" y="20" fontSize="75" fill="#FFFFFF" text={ this.props.txt } fontFamily='Montserrat' />
<Text x="20" y="125" lineHeight="1.25" width="300" fontSize="20" fontFamily='Roboto' fill="#fff" text={ this.props.content }/>
</Layer>
</Stage>
)
}
}
Hello, I have a problem with this functions ( moveUp and moveDown ).
Here is my workarround.
class MyImage extends Component {
constructor(props) {
super(props);
this.state = {
src: '',
image: null,
rotation: 0
};
this.onMouseDown = this.onMouseDown.bind(this);
}
componentDidMount() {
const image = new window.Image();
image.src = this.props.srcImage;
image.height = 150;
image.width = 150;
image.onload = () => {
this.setState({
image: image
});
};
}
onMouseDown(e) {
this.props.setActiveImage(e.target._id);
}
render() {
return (
<Group
draggable
onMouseDown={this.onMouseDown}
rotation={this.state.rotation}
opacity={1}
>
<Image
image={this.state.image}
/>
</Group>
);
}
}
When I mouseDown on Group with Image, I set a active image.
export function setActiveImage(id) {
return({
type: ACTIVE_IMAGE,
payload: id
});
}
Canvas is here. I map array with images and draw them. I click on Image and set active image, then I have PanelTools, where I have buttons like 'delete', 'clone', 'moveUp', 'moveDown' etc ... And this last two buttons not work like have. When I click on Image and then on button 'moveUp' or 'moveDown', image is pushing up and down (like I expected and should), but when I click back on canvas, images drop to their positions like were before.
layerImage(image) {
return(
<MyImage srcImage={image} />
);
}
onButtonClickAction(type) {
switch(type) {
case 'moveUp':
this.refs.layer.find('Image').map(image => {
if(image._id === this.props.activeImage.activeImage) {
image.parent.moveUp();
}
});
this.refs.layer.draw();
break;
case 'moveDown':
this.refs.layer.find('Image').map(image => {
if(image._id === this.props.activeImage.activeImage) {
image.parent.moveDown();
}
});
this.refs.layer.draw();
break;
default:
return false;
}
}
render() {
return(
<div>
<PanelTools onButtonClickAction={(type) => this.onButtonClickAction(type)}/>
<div ref="outer" className="outter-set">
<div className="inner-set">
<div id="fashion-designer" className="fashion-designer">
<Stage ref="stage" width={700} height={700} onContentClick={this.onStageClick}>
<Layer ref="layer">
{this.props.layerImages.map(this.layerImage)}
</Layer>
</Stage>
</div>
</div>
</div>
</div>
);
}
Thanks for any advices.
Every example I try gives same error.
Uncaught TypeError: Cannot read property 'add' of undefined
on the line
nativeParent.node.add(this.node);
var GroupMixin = {
mountComponent: function(transaction, nativeParent, nativeContainerInfo, context) {
this.node = new Konvathis.constructor.displayName;
nativeParent.node.add(this.node);
var props = this._initialProps;
this.applyNodeProps(emptyObject, props);
this.mountAndInjectChildren(props.children, transaction, context);
return {
App.js file is:
import React from 'react';
import ReactDOM from 'react-dom';
import {Layer, Rect, Stage, Group} from 'react-konva';
class MyRect extends React.Component {
constructor(...args) {
super(...args);
this.state = {
color: 'green'
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({
color: Konva.Util.getRandomColor()
});
}
render(){
return (
<Stage width={700} height={700}>
<Layer>
<MyRect/>
</Layer>
</Stage>
);
}
}
ReactDOM.render(, document.getElementById('main'));
I am trying to surround a Konva.Text
with a Konva.Rect
, which requires that I measure the text before drawing the rectangle. How would you recommend that I accomplish this?
Currently it requires two passes with React to first render the Text and then render the Rectangle, since I can't access the underlying Konva.Text
element before it is rendered.
It took me a while to figure this out, and I ended up resorting to ugly timeout hacks and forced re-renders of the component.
Would it be possible to tie the image object onload event to the redrawing of the shape? Or should ensuring image is fully loaded be the user's responsibility?
This is not really an issue but more like a suggestion. That would be great if this tool could generate a Canvas code based on the given JSX React components (e.i. converting JSC DOM to Canvas elements). I know this is lots of work.
I have app with 200 complex objects on one layer and it's really slow, in Konva docs i found Node caching, can i use this approach with react components
Hi,
This line to say thank you for the great job with react-konva.
However i'm encoutering this warning:
Warning: There is an internal error in the React performance measurement code. Did not expect componentWillUnmount timer to start while componentWillUnmount timer is still in progress for another instance.
I spent some time to find the trigger, and there it is:
class Child extends Component {
componentWillUnmount() {
}
render() {
return (
<Group />
);
}
}
class Parent extends Component {
render() {
return (
<Stage>
<Layer>
<Child />
</Layer>
</Stage>
);
}
}
When there is no componentWillUnmount method in Child, nothing happen. But when this method exists, React notices the warning above.
I tried to find more information on it, but i didn't find similiar issues, so here i am.
Might you help me to know what i'm doing wrong?
Many devices scale web content, so that what the browser naively thinks of a pixel could be 2x2, 3x3, etc pixels instead.
see: http://alistapart.com/article/a-pixel-identity-crisis
What this means for this library, is that graphics will not be rendered with optimal fidelity for any iOS, Retina MacBook, modern Android phone, etc.
Hi, according to http://konvajs.github.io/docs/drag_and_drop/Drag_a_Stage.html, it is possible to drag the Stage.
I tried the same thing with react-konva (code below) and it seems not working. Nothing is happening, drag events aren't firing etc.
Am I doing anything wrong or is it not working the same way in react-konva ?
I'm using react-konva v. 0.6.4 (cause I need react v0.14 in my project).
import React, {Component} from 'react';
import {Layer, Stage, Circle} from 'react-konva';
export default class Example extends Component {
handleDragStart = () => {
console.log('dragStart');
};
render() {
var width = window.innerWidth;
var height = window.innerHeight;
return (
<Stage
container = {'container'}
width = {width}
height = {height}
draggable = {true}
onDragStart = {this.handleDragStart}
>
<Layer>
<Circle
x = {width / 2}
y = {height / 2}
radius = {70}
fill = {'red'}
stroke = {'black'}
strokeWidth = {4}
/>
</Layer>
</Stage>
);
}
}
When running the example I receive "react-konva.js?092e:309Uncaught TypeError: Cannot read property 'add' of undefined"
Any ideas?
thanks
Hi there,
I would like to try rotation function on the image, so I create a simple click event on the image to call the rotate function. The problem I got is, the image won't rotate/draw unless I click it twice. I am pretty new to this, could somebody help me take a look:
jabin is right here
http://jsbin.com/muxofak/edit?js,output
To see the rotation, please drag the image away from the left up coner first.
Thanks very much
https://github.com/lavrton/react-konva/blob/master/src/react-konva.js#L224
This line of code expects "Image" to exist on the global scope.
When using jsdom, however, Image is not global, but under "window.Image".
A workaround is to copy Image to the global scope in the jsdom script:
...
const jsdom = require('jsdom').jsdom;
global.document = jsdom('');
global.window = document.defaultView;
...
global.Image = window.Image;
Suggest react-konva becomes more robust by checking Image || window.Image
would it be possible to add an example where you illustrate how to use for instance .setOffset on text in a react context?
`
var simpleText = new Konva.Text({
x: stage.getWidth() / 2,
y: 15,
text: 'Simple Text',
fontSize: 30,
fontFamily: 'Calibri',
fill: 'green'
});
// to align text in the middle of the screen, we can set the
// shape offset to the center of the text shape after instantiating it
simpleText.setOffset({
x: simpleText.getWidth() / 2
});
`
Hello. thank you for this nice library.
I've made a demo use react-konva, here is the online demo:
http://jy1989.github.io/demo/react-canvas-gol/
and the code
https://github.com/jy1989/react_game_of_life/blob/react-canvas/app/index.js
so I have no idea why the performance so bad
How can I check?
Terrific framework. I am currently trying to get mouse position of mouse onClick(offsetX/offsetY), and the classic e = e || window.event;, is returning the parameters for the element itself.
event: {"evt":{"isTrusted":true},"target":"{"attrs":{"width":400,"height":400},"className":"Rect"}","currentTarget":"{"attrs":{"width":400,"height":400},"className":"Rect"}","type":"click"}
Latest React (15.4.0) doesn't expose internals through react/lib
anymore:
modulesModuleNotFoundError: Module not found: Error: Cannot resolve module 'react/lib/ReactInstanceMap'
From React blog:
However, there is a possibility that you imported private APIs from react/lib/*, or that a package you rely on might use them. We would like to remind you that this was never supported, and that your apps should not rely on internal APIs. The React internals will keep changing as we work to make React better.
Hello, I am running into issues regarding layering. Using the Konva library directly, I am able to manipulate react-konva components layering using methods such as .moveToTop() and can see it is working in browser via debugger statements. However, as soon as I re-render my component, all the layering is reset. I should also note that I have been performing the layering tweaks inside the render method of the component. I have experimented with re-ordering the creation of components as well as their ordering within a Layer/Stage to no avail. Whats the proper way to specify the z-index of a given react-konva component?
Demo with a workaround: http://jsbin.com/xoqomutiro/edit?js,console,output
<Stage ref='stage' width={width} height={height} onContentMouseDown={this.onMouseDown}>
<Layer ref='imageLayer' />
<Layer ref='measLayer' />
</Stage>
i write a demo for it:
Demo
hi,bro,I like your react-konva,can you expose a shape of arrow in your lib, so i can use like this:
import {Arrow} from 'react-konva';
Seems like you use a lot of private methods and APIs that aren't exposed by preact-compat
(and, by the way, shouldn't be used neither with React since they are private).
Do you have plans to move the code to a full public-API code?
Hello, i have problem with building Meteor app.
I still receiving message
Unable to resolve some modules:
"../build/Release/canvas"
Can you help me with this problem? I have finished application and big problem with this issue, cause im not able to deploy this app to production!
Thank you
Hi!
Few hours ago new version of react-konva were published in npm and it requeirs now react 15.4.0 as peer dependency instead of 15.1.0.
It could be assumed as breaking change, so I wanna ask why you did such changes under same minor version of the library?
I would like to create my own components that render using react-konva, and also have a parent child relationship. For example:
class Frame extends React.Component {
render() {
return (
<Layer x={10} y={10}>
<Rect width={50} height={30} stroke={'black'} />
<Artwork />
</Layer>
)
}
}
class Artwork extends React.Component {
render() {
return ( <Rect x={5} y={5} width={40} height={20} fill={'red'} /> )
}
}
This seems to mostly work, except the child konva components don't seem to be connected to their parent konva components. This causes relative position, scale, rotation, etc. to be lost.
The error in chrome console
only-dev-server.js:74 [HMR] Waiting for update signal from WDS...
react-konva.js:329 Uncaught TypeError: Cannot read property 'add' of undefined
client:37 [WDS] Hot Module Replacement enabled.
My Js
import React from 'react';
import ReactDOM from 'react-dom';
import {Layer, Rect, Stage, Group} from 'react-konva';
class MyRect extends React.Component {
constructor(...args) {
super(...args);
this.state = {
color: 'green'
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({
color: Konva.Util.getRandomColor()
});
}
render() {
return (
<Rect
x={10} y={10} width={50} height={50}
fill={this.state.color}
shadowBlur={10}
onClick={this.handleClick}
/>
);
}
}
function App() {
// Stage - is a div wrapper
// Layer - is a <canvas> element on the page
// so you can use several canvases. It may help you to improve performance a lot.
return (
<Stage width={700} height={700}>
<Layer>
<MyRect/>
</Layer>
</Stage>
);
}
ReactDOM.render(<App/>, document.getElementById('root'));
My Html
<!doctype html>
<html>
<head>
<title>Sample App</title>
</head>
<body>
<div id='root'>
</div>
<script src="/static/bundle.js"></script>
</body>
</html>
Anyway to get the Stage width and height to fit it's container?
e.g. <Stage ref={(s) => { this.stage = s; }} width={'100%'}>
Can the children also therefore react to the width and height of the stage?
e.g. <Image width={this.stage.width / 2} />
I want to have clean canvas at the begining and I want to add drag and drop images to canvas layer. How can I do this?
Thanks for reply :)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.