Skip to content

Commit ef40e44

Browse files
committed
feat: 实现三角形工具
1 parent 5828426 commit ef40e44

File tree

2 files changed

+43
-2
lines changed

2 files changed

+43
-2
lines changed

packages/core/src/tools/triangle-tool.ts

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,45 @@
1+
import { Triangle } from '../customs/triangle';
12
import { Tool } from '../types';
3+
import { Point } from '../utils';
4+
5+
import { selectTool } from './select-tool';
26

37
export const triangleTool = (): Tool => {
8+
const startPointer: Point = new Point(0, 0);
9+
const triangle: Triangle = new Triangle({
10+
fill: 'transparent',
11+
stroke: 'black',
12+
strokeWidth: 2,
13+
sides: 3,
14+
radius: 0,
15+
});
16+
417
return {
518
name: 'triangleTool',
6-
onActive() {},
7-
onInactive() {},
19+
onActive(app) {
20+
app.cancelSelect();
21+
},
22+
onInactive() {
23+
startPointer.setXY(0, 0);
24+
},
25+
onMouseDown({ app }) {
26+
startPointer.clone(app.pointer);
27+
triangle.setPosition(startPointer);
28+
app.add(triangle);
29+
},
30+
onMouseMove({ app }) {
31+
// 计算起点和当前鼠标位置之间的距离
32+
const dx = app.pointer.x - startPointer.x;
33+
const dy = app.pointer.y - startPointer.y;
34+
35+
// 计算椭圆的宽度和高度的绝对值
36+
triangle.setPosition(new Point(startPointer.x + dx / 2, startPointer.y + dy / 2));
37+
triangle.radius(startPointer.distanceTo(app.pointer));
38+
app.render();
39+
},
40+
onMouseUp({ app }) {
41+
app.setTool(selectTool(triangle));
42+
},
843
};
944
};
1045

packages/core/src/utils/math.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,12 @@ export class Point implements Konva.Vector2d {
2626
return this.x === point.x && this.y === point.y;
2727
}
2828

29+
public distanceTo(point: Point): number {
30+
const dx = this.x - point.x;
31+
const dy = this.y - point.y;
32+
return Math.sqrt(dx * dx + dy * dy);
33+
}
34+
2935
public toArray(): number[] {
3036
return [this.x, this.y];
3137
}

0 commit comments

Comments
 (0)