forked from Secretmapper/react-image-annotation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RectangleSelector.js
99 lines (84 loc) · 2.06 KB
/
RectangleSelector.js
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
96
97
98
99
const getCoordPercentage = (e) => ({
x: e.nativeEvent.offsetX / e.currentTarget.offsetWidth * 100,
y: e.nativeEvent.offsetY / e.currentTarget.offsetHeight * 100
})
export const TYPE = 'RECTANGLE'
export function intersects ({ x, y }, geometry) {
if (x < geometry.x) return false
if (y < geometry.y) return false
if (x > geometry.x + geometry.width)
return false
if (y > geometry.y + geometry.height)
return false
return true
}
export function area (geometry) {
return geometry.height * geometry.width
}
export const methods = {
onMouseDown (annotation, e) {
if (!annotation.selection) {
const { x: anchorX, y: anchorY } = getCoordPercentage(e)
return {
...annotation,
selection: {
...annotation.selection,
mode: 'SELECTING',
anchorX,
anchorY
}
}
} else {
return {}
}
return annotation
},
onMouseUp (annotation, e) {
if (annotation.selection) {
const { selection, geometry } = annotation
if (!geometry) {
return {}
}
switch (annotation.selection.mode) {
case 'SELECTING':
return {
...annotation,
selection: {
...annotation.selection,
showEditor: true,
mode: 'EDITING'
}
}
default:
break
}
}
return annotation
},
onMouseMove (annotation, e) {
if (annotation.selection && annotation.selection.mode === 'SELECTING') {
const { anchorX, anchorY } = annotation.selection
const { x: newX, y: newY } = getCoordPercentage(e)
const width = newX - anchorX
const height = newY - anchorY
return {
...annotation,
geometry: {
...annotation.geometry,
type: TYPE,
x: width > 0 ? anchorX : newX,
y: height > 0 ? anchorY : newY,
width: Math.abs(width),
height: Math.abs(height)
}
}
}
return annotation
}
}
export default {
TYPE,
intersects,
area,
methods
}