Skip to content

Commit

Permalink
feat: 新增铅笔工具
Browse files Browse the repository at this point in the history
  • Loading branch information
Yan Heng committed Aug 1, 2023
1 parent aedb12a commit 98b6394
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 6 deletions.
39 changes: 37 additions & 2 deletions packages/core/src/tools/drawing-tool.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,45 @@
import Konva from 'konva';

import { Tool } from '../types';
import { Point } from '../utils';

import { selectTool } from './select-tool';

export const drawingTool = (): Tool => {
let points: Point[] = [];
const line = new Konva.Line({
stroke: 'black',
strokeWidth: 2,
globalCompositeOperation: 'source-over',
lineCap: 'round',
lineJoin: 'round',
});

const flatPoints = (): number[] => points.reduce<number[]>((points, point) => [...points, ...point.toArray()], []);

return {
name: 'drawingTool',
onActive() {},
onInactive() {},
onActive(app) {
app.select();
},
onInactive() {
points = [];
},
onMouseDown({ app }): void {
const lastPoint = points.at(-1);
if (!lastPoint || !lastPoint.eq(app.pointer)) {
points.push(app.pointer);
}
line.points(flatPoints());
app.add(line);
},
onMouseMove({ app, event }): void {
event.evt.stopPropagation();
line.points(line.points().concat([app.pointer.x, app.pointer.y]));
},
onMouseUp({ app }): void {
app.setTool(selectTool(line));
},
};
};

Expand Down
8 changes: 4 additions & 4 deletions packages/core/src/tools/line-tool.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Line } from '../customs/line';
import { AppMouseEvent, Tool } from '../types';
import { Tool } from '../types';
import { Point } from '../utils';

import { selectTool } from './select-tool';
Expand All @@ -19,7 +19,7 @@ export const lineTool = (): Tool => {
line = null;
points = [];
},
onMouseDown({ app }: AppMouseEvent): void {
onMouseDown({ app }): void {
const lastPoint = points.at(-1);
if (!lastPoint || !lastPoint.eq(app.pointer)) {
points.push(app.pointer);
Expand All @@ -36,14 +36,14 @@ export const lineTool = (): Tool => {
app.add(line);
}
},
onMouseMove({ app }: AppMouseEvent): void {
onMouseMove({ app }): void {
if (!line) {
return;
}
line.points(flatPoints().concat(app.pointer.x, app.pointer.y));
app.render();
},
onMouseDoubleClick({ app }: AppMouseEvent): void {
onMouseDoubleClick({ app }): void {
if (!line) {
return;
}
Expand Down

0 comments on commit 98b6394

Please sign in to comment.