Coder Social home page Coder Social logo

konvajs / react-konva Goto Github PK

View Code? Open in Web Editor NEW
5.6K 61.0 250.0 2.63 MB

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

Home Page: https://konvajs.github.io/docs/react/

License: MIT License

JavaScript 1.77% TypeScript 97.11% HTML 1.12%
konva draw-graphics react canvas konva-framework visualization

react-konva's Introduction

React Konva

Build Status Greenkeeper badge

ReactKonva Logo

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, { useState } from 'react';
import { render } from 'react-dom';
import { Stage, Layer, Rect, Text } from 'react-konva';
import Konva from 'konva';

const ColoredRect = () => {
  const [color, setColor] = useState('green');

  const handleClick = () => {
    setColor(Konva.Util.getRandomColor());
  };

  return (
    <Rect
      x={20}
      y={20}
      width={50}
      height={50}
      fill={color}
      shadowBlur={5}
      onClick={handleClick}
    />
  );
};

const App = () => {
  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.

import React, { useEffect, useRef } from 'react';

const MyShape = () => {
  const circleRef = useRef();

  useEffect(() => {
    // log Konva.Circle instance
    console.log(circleRef.current);
  }, []);

  return <Circle ref={circleRef} 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:

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

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

Demo: https://codesandbox.io/s/6l97wny44z

Usage with Next.js

Note: react-konva is designed to work in the client-side. On the server side, it will render just empty div. So it doesn't make much sense to use react-konva for server-side rendering. In Next.js you may have issue like

Module not found: Can't resolve 'canvas'

Why do we see this error? canvas module is used for canvas rendering in Node.JS environment. konva library will use it there, but it doesn't have this dependency explicitly.

Use dynamic loading

Next.js docs: https://nextjs.org/docs/pages/building-your-application/optimizing/lazy-loading

With this approach your canvas component will be loaded on the client-side only. So you will not have any issues with server-side rendering. Also next.js will automatically understand that it doesn't need to load canvas module, because it is used for server-side rendering only.

Step 1 - Create canvas component

You need to define your canvas components somewhere in your components folder.

It must be placed outside of pages or app folder (because they are used for server rendering).

Your components/canvas.js file may look like this:

import { Stage, Layer, Circle } from 'react-konva';

function Canvas(props) {
  return (
    <Stage width={window.innerWidth} height={window.innerHeight}>
      <Layer>
        <Circle x={200} y={100} radius={50} fill="green" />
      </Layer>
    </Stage>
  );
}

export default Canvas;

Step 2 - Use dynamic import

Then you can use it in your page. Notice, it is imported to have 'use client';.

'use client';
import dynamic from 'next/dynamic';

const Canvas = dynamic(() => import('../components/canvas'), {
  ssr: false,
});

export default function Page(props) {
  return <Canvas />;
}

Step 3 - Setup next.config.js

In some versions of next.js you may need to set up next.config.js to make it work:

/** @type {import('next').NextConfig} */
const nextConfig = {
  webpack: (config) => {
    config.externals = [...config.externals, { canvas: 'canvas' }]; // required to make Konva & react-konva work
    return config;
  },
};

module.exports = nextConfig;

Usage with React Context

Note: this section may be not relevant, because this issue was fixed in [email protected]. So context should work by default.

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.


react-konva's People

Contributors

alexkuz avatar allada avatar davvidbaker avatar dylanarmstrong avatar easybreezy97 avatar ejarzo avatar greenkeeper[bot] avatar greenkeeperio-bot avatar intellidev1991 avatar jamiemchale avatar jet-set-willy avatar joeduncko avatar jondegn avatar julien-prado avatar kiyopikko avatar lavrton avatar maritaria avatar markov00 avatar methuselah96 avatar michaeldeboey avatar nsharma1396 avatar pastelmind avatar rafaelalmeidatk avatar rokoroku avatar stues avatar tuoxiansp avatar tyler-johnson avatar yalab avatar yrymrr avatar zephd avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-konva's Issues

Support content event

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.

Mouse event fired when evt.handler is null

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.

Layering destroyed on render

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?

Changed peer dependency in 1.0.9

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?

Cannot use package from npm

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?

JSC support

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.

ReactDebugTool: debugID may not be empty

I am using react-konva with golden-layout. And I get a lot of error like this:

At the begin it will throw something error like this:
image

and later, it is all like this.
image

So I am wondering, what's the potential reason that called this problem? and how can I solve this issue?

Testing with Jest Snapshot

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)

Unable to resolve some modules: "canvas" and "jsdom"

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

Please verify Image component loading behaviour

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.

Can not add events to Stage

<Stage ref='stage' width={width} height={height} onContentMouseDown={this.onMouseDown}>
     <Layer ref='imageLayer' />
     <Layer ref='measLayer' />
</Stage>

i write a demo for it:
Demo

no Arrow defined in your lib

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';

ReactKonva.Image component needs a fully loaded Image() object to work

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?

Stage level event does not seem to be working

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!

Scale whole canvas?

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.

Using with electron

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'));

Filters on Image

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>
     )
  }

}



Minimize the bundle size

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.

Dynamic Size

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} />

Problem with Canvas

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

Image not defined when testing

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?

Event handler that opens up native canvas element

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"}

[question] is react-konva practical for creating user interfaces?

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. :)

Image not defined (testing using jsdom)

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

Nesting user components and react-konva components

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.

Example using library functions in react

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
});
`

measureText()

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.

Compatibility with preact?

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?

demo cannot run

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>


how to set two rect with 2 zIndex?

      <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.

Stage dragging

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>
    );
  }
}

Not compatible with new version of React (15.4.0)

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.

componentWillUnmount

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?

moveUp() and moveDown() not work corectlly

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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.