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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import React, { useCallback, useState } from 'react';
import type { NextPage } from 'next';
import { Page, Container, Canvas, Toolbar } from 'components/content';
import { View, Layer, Circle, Rectangle, Tool } from 'react-paper-bindings';
import { Color } from 'paper/dist/paper-core';
import { Button } from 'react-daisyui';
function random(min: number, max: number) {
return Math.floor(Math.random() * (max - min)) + min;
}
function randomColor() {
const rgb = `rgb(${random(0, 255)},${random(0, 255)},${random(0, 255)})`;
return new Color(rgb).toCSS(true);
}
type ICircle = {
id: number;
type: 'Circle';
center: paper.Point | [number, number];
radius: number;
fillColor: any;
};
type IRectangle = {
id: number;
type: 'Rectangle';
center: paper.Point | [number, number];
size: [number, number] | number;
fillColor: any;
};
type Item = ICircle | IRectangle;
type Tool = 'Rectangle' | 'Circle';
const ToolsPage: NextPage = () => {
const [activeTool, setActiveTool] = useState<Tool>('Rectangle');
const [items, setItems] = useState<Item[]>([]);
const handleCircleMouseDown = useCallback(
(e: paper.ToolEvent) => {
setItems([
...items,
{
id: items.length + 1,
type: 'Circle',
center: [e.point.x, e.point.y],
radius: random(3, 30),
fillColor: randomColor(),
},
]);
},
[items]
);
const handleRectangleMouseDown = useCallback(
(e: paper.ToolEvent) => {
setItems([
...items,
{
id: items.length + 1,
type: 'Rectangle',
center: [e.point.x, e.point.y],
size: random(10, 40),
fillColor: randomColor(),
},
]);
},
[items]
);
return (
<Page title="Tools">
<Container>
<Toolbar>
<Button
size="sm"
color={activeTool === 'Rectangle' ? 'primary' : 'ghost'}
className="mr-2"
onClick={() => setActiveTool('Rectangle')}
>
Rectangle
</Button>
<Button
size="sm"
className="mr-2"
color={activeTool === 'Circle' ? 'primary' : 'ghost'}
onClick={() => setActiveTool('Circle')}
>
Circle
</Button>
</Toolbar>
<Canvas>
<View>
<Layer>
{items.map((props) =>
props.type === 'Rectangle' ? (
<Rectangle key={props.id} {...props} />
) : (
<Circle key={props.id} {...props} />
)
)}
</Layer>
</View>
<Tool
name="Rectangle"
active={activeTool === 'Rectangle'}
onMouseDown={handleRectangleMouseDown}
/>
<Tool
name="Circle"
active={activeTool === 'Circle'}
onMouseDown={handleCircleMouseDown}
/>
</Canvas>
</Container>
</Page>
);
};
export default ToolsPage;