【问题标题】:The issue with drawing straight line and rectangle in Konvajs React在 Konvajs React 中绘制直线和矩形的问题
【发布时间】:2020-10-08 08:49:14
【问题描述】:

我想在 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>
    );
  }
}

【问题讨论】:

  • 你找到解决办法了吗?

标签: reactjs konvajs-reactjs


【解决方案1】:

直线替换这个

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

有了这个

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-22
    • 2021-12-18
    • 1970-01-01
    • 2011-08-26
    • 1970-01-01
    • 1970-01-01
    • 2019-09-01
    • 1970-01-01
    相关资源
    最近更新 更多