显示用户在 react konva 中点击的形状

display shapes where user clicks in react konva

我是 react konva 的初学者,正在尝试做一个简单的项目。我只想在用户点击的任何地方显示一个矩形,如果用户点击 3 个位置,他可以在 canvas 上看到 3 个矩形。 我怎样才能做到这一点?

我在沙盒中找到这段代码并添加了一个 onmousedown handleclick 函数,但不知道下一步该做什么

非常感谢任何帮助

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

您需要为创建的矩形创建一个状态,在单击时将新数据添加到状态,并在渲染函数中从该状态绘制形状。

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