|
| 1 | +import { fabric } from 'fabric'; |
| 2 | + |
1 | 3 | import { Rect } from '../customs/rect';
|
2 | 4 | import { AppMouseEvent, ToolStrategy } from '../types';
|
3 | 5 |
|
4 | 6 | export class RectTool implements ToolStrategy {
|
5 |
| - private isDrawing: boolean = false; |
6 |
| - private rect: Rect | null = null; |
| 7 | + private startPointer: fabric.Point = new fabric.Point(0, 0); |
| 8 | + private rectangle: Rect | null = null; |
7 | 9 |
|
8 | 10 | public onMouseDown({ app }: AppMouseEvent): void {
|
9 |
| - this.isDrawing = true; |
10 |
| - const pointer = app.pointer; |
11 |
| - this.rect = new Rect({ |
12 |
| - left: pointer.x, |
13 |
| - top: pointer.y, |
14 |
| - width: 0, |
15 |
| - height: 0, |
| 11 | + this.startPointer = app.pointer; |
| 12 | + this.rectangle = new Rect({ |
| 13 | + left: this.startPointer.x, |
| 14 | + top: this.startPointer.y, |
| 15 | + width: 10, |
| 16 | + height: 10, |
16 | 17 | fill: 'transparent',
|
17 | 18 | stroke: 'black',
|
18 | 19 | strokeWidth: 2,
|
19 | 20 | });
|
20 |
| - app.canvas.add(this.rect); |
| 21 | + app.canvas.add(this.rectangle); |
21 | 22 | }
|
22 | 23 |
|
23 | 24 | public onMouseMove({ app }: AppMouseEvent): void {
|
24 |
| - if (!this.isDrawing || !this.rect) { |
| 25 | + if (!this.rectangle) { |
25 | 26 | return;
|
26 | 27 | }
|
27 |
| - const pointer = app.pointer; |
28 |
| - this.rect.set({ |
29 |
| - width: pointer.x - (this.rect.left ?? 0), |
30 |
| - height: pointer.y - (this.rect.top ?? 0), |
31 |
| - }); |
| 28 | + app.canvas.discardActiveObject(); |
| 29 | + app.render(); |
| 30 | + const width = app.pointer.x - this.startPointer.x; |
| 31 | + const height = app.pointer.y - this.startPointer.y; |
| 32 | + this.rectangle.set({ width, height }); |
32 | 33 | app.render();
|
33 | 34 | }
|
34 | 35 |
|
35 | 36 | public onMouseUp(): void {
|
36 |
| - this.isDrawing = false; |
37 |
| - this.rect = null; |
| 37 | + this.rectangle = null; |
38 | 38 | }
|
39 | 39 | }
|
40 | 40 |
|
|
0 commit comments