-
Notifications
You must be signed in to change notification settings - Fork 0
/
InputArea.tsx
95 lines (86 loc) · 2.39 KB
/
InputArea.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import React, { useState, useRef } from "react";
import { Layer, Stage, Rect } from "react-konva";
import { useSetBoxesProps } from "./contextData";
import Konva from "konva";
import { Vector2d } from "konva/types/types";
import { getRelativePointerPosition } from "./konvaFunctions";
const SelectionRect: React.FC<{
beginPos: Vector2d;
endPos: Vector2d;
}> = ({ beginPos, endPos }) => {
return (
<Rect
x={beginPos.x}
y={beginPos.y}
width={endPos.x - beginPos.x}
height={endPos.y - beginPos.y}
fill={"blue"}
stroke={"red"}
opacity={0.2}
/>
);
};
const InputArea: React.FC<{
layoutSize: RectSize;
}> = ({ layoutSize }) => {
const setBoxesProps = useSetBoxesProps();
const [mouseDownPos, setMouseDownPos] = useState<Vector2d>({ x: 0, y: 0 });
const [dragging, setDragging] = useState<Boolean>(false);
const inputAreaRef = useRef<Konva.Stage>(null);
const addBoxProps = () => {
const mouseUpPos = getRelativePointerPosition(inputAreaRef) ?? {
x: 0,
y: 0,
};
setBoxesProps((preState) => [
...preState,
(() => {
// 左上頂点で座標を管理
const x = Math.min(mouseDownPos.x, mouseUpPos.x);
const y = Math.min(mouseDownPos.y, mouseUpPos.y);
const width = Math.abs(mouseDownPos.x - mouseUpPos.x);
const height = Math.abs(mouseDownPos.y - mouseUpPos.y);
return {
key: preState.length,
cropX: x,
cropY: y,
cropWidth: width,
cropHeight: height,
x,
y,
width,
height,
};
})(),
]);
};
return (
<Stage
className="input-area"
width={layoutSize.width}
height={layoutSize.height}
ref={inputAreaRef}
onMouseDown={() => {
setMouseDownPos(
getRelativePointerPosition(inputAreaRef) ?? { x: 0, y: 0 }
);
setDragging(true);
}}
onMouseUp={() => {
addBoxProps();
setDragging(false);
}}
>
<Layer>
{dragging ? (
<SelectionRect
beginPos={mouseDownPos}
endPos={getRelativePointerPosition(inputAreaRef) ?? { x: 0, y: 0 }}
// FIXME: endPosの更新タイミングで描画されず、baseCanvasの更新により描画されている。
/>
) : null}
</Layer>
</Stage>
);
};
export default InputArea;