Skip to content

Commit

Permalink
Merge pull request #2 from goveo/feature/stroke-callbacks
Browse files Browse the repository at this point in the history
Provide stroke callbacks
  • Loading branch information
ascorbic authored Jul 8, 2021
2 parents e573049 + 36b4654 commit 4442c3a
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,18 @@ export function App() {
Canvas rendering context
- **`onStartStroke`**: `(point: Point) => void`
Callback at the start of a stroke
- **`onContinueStroke`**: `(point: Point) => void`
Callback at the continuing of a stroke
- **`onEndStroke`**: `() => void`
Callback at the end of a stroke
### Paintbrush
`useBrush(options)`
Expand Down
22 changes: 18 additions & 4 deletions src/components/Artboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ export interface ArtboardProps
extends React.CanvasHTMLAttributes<HTMLCanvasElement> {
tool: ToolHandlers;
history?: History;
onStartStroke?: (point: Point) => void;
onContinueStroke?: (point: Point) => void;
onEndStroke?: () => void;
}

export interface ArtboardRef {
Expand All @@ -37,7 +40,15 @@ export interface ToolHandlers {
}

export const Artboard = forwardRef(function Artboard(
{ tool, style, history, ...props }: ArtboardProps,
{
tool,
style,
history,
onStartStroke,
onContinueStroke,
onEndStroke,
...props
}: ArtboardProps,
ref: ForwardedRef<ArtboardRef>
) {
const [context, setContext] = useState<CanvasRenderingContext2D | null>();
Expand All @@ -52,8 +63,9 @@ export const Artboard = forwardRef(function Artboard(
context.save();
setDrawing(true);
tool.startStroke?.(point, context);
onStartStroke?.(point);
},
[tool, context]
[tool, context, onStartStroke]
);

const continueStroke = useCallback(
Expand All @@ -62,20 +74,22 @@ export const Artboard = forwardRef(function Artboard(
return;
}
tool.continueStroke?.(newPoint, context);
onContinueStroke?.(newPoint);
},
[tool, context]
[tool, context, onContinueStroke]
);

const endStroke = useCallback(() => {
setDrawing(false);
if (context) {
tool.endStroke?.(context);
onEndStroke?.();
context.restore();
if (canvas && history) {
history.pushState(canvas);
}
}
}, [tool, context, canvas, history]);
}, [tool, context, canvas, history, onEndStroke]);

const mouseMove = useCallback(
(event: React.MouseEvent<HTMLCanvasElement, MouseEvent>) => {
Expand Down

0 comments on commit 4442c3a

Please sign in to comment.