2

我想在 React 中创建绘图应用程序,为了实现这一目标,我遇到了一个叫做 Konvajs 的东西。然后,我开始并以某种方式实现了我可以画出这样的非直线在此处输入图像描述

但我想画的是这样的直线在此处输入图像描述

和矩形。这是我的代码:

import React, { Component } from "react";
import { Stage, Layer, Line, Rect, Text } from "react-konva";
export default class Canvas extends Component {
  state = {
    lines: [],
  };
  handleMouseDown = () => {
    this._drawing = true;
    this.setState({
      lines: [...this.state.lines, []],
    });
  };
  handleMouseUp = () => {
    this._drawing = false;
  };
  handleMouseMove = (e) => {
    if (!this._drawing) {
      return;
    }
    const stage = this.stageRef.getStage();
    const point = stage.getPointerPosition();
    const { lines } = this.state;
    let lastLine = lines[lines.length - 1];
    lastLine = lastLine.concat([point.x, point.y]);
    lines.splice(lines.length - 1, 1, lastLine);
    this.setState({
      lines: lines.concat(),
    });
  };
  render() {
    return (
      <Stage
        width={window.innerWidth}
        height={window.innerHeight}
        onContentMousedown={this.handleMouseDown}
        onContentMousemove={this.handleMouseMove}
        onContentMouseup={this.handleMouseUp}
        ref={(node) => {
          this.stageRef = node;
        }}
      >
        <Layer>
          <Text text="Draw a thing!" />
          {this.state.lines.map((line, i) => (
            <Line key={i} points={line} stroke="red" />
          ))}
        </Layer>
      </Stage>
    );
  }
}
4

1 回答 1

1

对于直线替换这个

lastLine = lastLine.concat([point.x, point.y]);

有了这个

lastLine = [lastLine[0], lastLine[1], point.x, point.y]

基本上,你最多应该有四分。前两个是 OnMouseDown 创建的,后两个应该在您移动光标时更新 - OnMouseMove

于 2021-06-02T00:39:05.837 回答