Reputation: 68
I am a complete beginner in react konva and trying to make a simple project. I just want to display a rectangle wherever user clicks so like if user clicked at 3 position he can see 3 rectangle on the canvas. How can I achieve this?
I found this code in sandbox and added a onmousedown handleclick function but have no idea what to do next
any help is much appreciated
import React, { Component } from "react";
import Konva from "konva";
import { render } from "react-dom";
import { Stage, Layer, Rect, Text } from "react-konva";
class App extends Component {
state = {
cursor: {
x: null,
y: null
}
};
handleClick = (e) => {
alert("mouseclicked");
};
handleMouseMove = (e) => {
var stage = e.currentTarget;
stage = this.stageRef.getStage();
stage = e.target.getStage();
this.setState({
cursor: stage.getPointerPosition()
});
};
render() {
const text = `cursor position : ${this.state.cursor.x}, ${this.state.cursor.y}`;
return (
<Stage
onMouseDown={this.handleClick}
width={window.innerWidth}
height={window.innerHeight}
onMouseMove={this.handleMouseMove}
ref={(ref) => {
this.stageRef = ref;
}}
>
<Layer>
<Text text={text} x={50} y={100} fontSize={20} />
</Layer>
</Stage>
);
}
}
render(<App />, document.getElementById("root"));
Upvotes: 0
Views: 1071
Reputation: 20288
You need to have a state for created rectangles, add new data into state on click and draw shapes from that state in render function.
import React, { Component } from "react";
import Konva from "konva";
import { render } from "react-dom";
import { Stage, Layer, Rect, Text } from "react-konva";
class App extends Component {
state = {
cursor: {
x: null,
y: null
},
rectangles: []
};
handleClick = (e) => {
const newRect = {
width: 100,
height: 100,
fill: Konva.Util.getRandomColor(),
x: e.target.getStage().getPointerPosition().x,
y: e.target.getStage().getPointerPosition().y
};
const rectangles = [...this.state.rectangles, newRect];
this.setState({ rectangles });
};
handleMouseMove = (e) => {
var stage = e.currentTarget;
stage = this.stageRef.getStage();
stage = e.target.getStage();
this.setState({
cursor: stage.getPointerPosition()
});
};
render() {
const text = `cursor position : ${this.state.cursor.x}, ${this.state.cursor.y}`;
return (
<Stage
onMouseDown={this.handleClick}
width={window.innerWidth}
height={window.innerHeight}
onMouseMove={this.handleMouseMove}
ref={(ref) => {
this.stageRef = ref;
}}
>
<Layer>
<Text text={text} x={50} y={100} fontSize={20} />
{this.state.rectangles.map((shape) => (
<Rect {...shape} />
))}
</Layer>
</Stage>
);
}
}
render(<App />, document.getElementById("root"));
https://codesandbox.io/s/react-konva-add-shapes-on-click-n0641?file=/src/index.js
Upvotes: 2