2

I wanted to create drawing app in React and to achieve that I came across something called Konvajs. Then, I started and somehow achieved that I can draw non-straight lines like this enter image description here

But what I wanted to draw is straight lines like this enter image description here

and rectangle. Here is my code:

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

1 Answers1

2

For straight lines replace this

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

With this

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

Basically, you should have maximum four points. The first two are created OnMouseDown and the last two should be updated as you are moving the cursor - OnMouseMove

Steve Mclean
  • 149
  • 1
  • 12