Skip to content

Commit b5b6a96

Browse files
psychedelicioushipsterusername
authored andcommitted
feat(ui): dynamic brush spacing
Scaled to 10% of brush size, clamped between 5px and 15px. This makes drawing feel a bit smoother, but maintains reasonable performance.
1 parent 806a8f6 commit b5b6a96

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

invokeai/frontend/web/src/features/controlLayers/hooks/mouseEventHooks.ts

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@ import {
1515
import type Konva from 'konva';
1616
import type { KonvaEventObject } from 'konva/lib/Node';
1717
import type { Vector2d } from 'konva/lib/types';
18-
import { useCallback, useRef } from 'react';
18+
import { clamp } from 'lodash-es';
19+
import { useCallback, useMemo, useRef } from 'react';
1920

2021
const getIsFocused = (stage: Konva.Stage) => {
2122
return stage.container().contains(document.activeElement);
@@ -67,7 +68,9 @@ const syncCursorPos = (stage: Konva.Stage): Vector2d | null => {
6768
return pos;
6869
};
6970

70-
const BRUSH_SPACING = 20;
71+
const BRUSH_SPACING_PCT = 10;
72+
const MIN_BRUSH_SPACING_PX = 5;
73+
const MAX_BRUSH_SPACING_PX = 15;
7174

7275
export const useMouseEvents = () => {
7376
const dispatch = useAppDispatch();
@@ -83,6 +86,10 @@ export const useMouseEvents = () => {
8386
const lastCursorPosRef = useRef<[number, number] | null>(null);
8487
const shouldInvertBrushSizeScrollDirection = useAppSelector((s) => s.canvas.shouldInvertBrushSizeScrollDirection);
8588
const brushSize = useAppSelector((s) => s.controlLayers.present.brushSize);
89+
const brushSpacingPx = useMemo(
90+
() => clamp(brushSize / BRUSH_SPACING_PCT, MIN_BRUSH_SPACING_PX, MAX_BRUSH_SPACING_PX),
91+
[brushSize]
92+
);
8693

8794
const onMouseDown = useCallback(
8895
(e: KonvaEventObject<MouseEvent>) => {
@@ -158,7 +165,7 @@ export const useMouseEvents = () => {
158165
// Continue the last line
159166
if (lastCursorPosRef.current) {
160167
// Dispatching redux events impacts perf substantially - using brush spacing keeps dispatches to a reasonable number
161-
if (Math.hypot(lastCursorPosRef.current[0] - pos.x, lastCursorPosRef.current[1] - pos.y) < BRUSH_SPACING) {
168+
if (Math.hypot(lastCursorPosRef.current[0] - pos.x, lastCursorPosRef.current[1] - pos.y) < brushSpacingPx) {
162169
return;
163170
}
164171
}
@@ -171,7 +178,7 @@ export const useMouseEvents = () => {
171178
$isDrawing.set(true);
172179
}
173180
},
174-
[dispatch, selectedLayerId, selectedLayerType, tool]
181+
[brushSpacingPx, dispatch, selectedLayerId, selectedLayerType, tool]
175182
);
176183

177184
const onMouseLeave = useCallback(

0 commit comments

Comments
 (0)