开源白板工具(SaaS),一体化白板,包含思维导图、流程图、自由画等。All in one open-source whiteboard tool with mind, flowchart, freehand and etc.
feat(freehand): optimize freehand curve by stylus features (#63)
pubuzhixing8665410718759
diff --git a/packages/drawnix/src/plugins/freehand/freehand.generator.ts b/packages/drawnix/src/plugins/freehand/freehand.generator.tsindex e8de926..7442333 100644--- a/packages/drawnix/src/plugins/freehand/freehand.generator.ts+++ b/packages/drawnix/src/plugins/freehand/freehand.generator.ts@@ -8,7 +8,7 @@ export class FreehandGenerator extends Generator<Freehand> {protected draw(element: Freehand): SVGGElement | undefined {const option: Options = { ...DefaultFreehand };const g = PlaitBoard.getRoughSVG(this.board).curve(- gaussianSmooth(element.points, 3, 9),+ gaussianSmooth(element.points, 1, 3),option);setStrokeLinecap(g, 'round');diff --git a/packages/drawnix/src/plugins/freehand/smoother.ts b/packages/drawnix/src/plugins/freehand/smoother.tsindex 328e621..e9f0ed1 100644--- a/packages/drawnix/src/plugins/freehand/smoother.ts+++ b/packages/drawnix/src/plugins/freehand/smoother.ts@@ -1,136 +1,254 @@-import { Point } from '@plait/core';--export interface FreehandSmootherConfig {- smoothing: number; // 基础平滑系数- velocityWeight: number; // 速度权重- curvatureWeight: number; // 曲率权重- maxPoints: number; // 最大历史点数- minDistance: number; // 最小距离阈值+import { distanceBetweenPointAndPoint, Point } from '@plait/core';++interface StrokePoint {+ point: Point;+ pressure?: number;+ timestamp: number;+ tiltX?: number;+ tiltY?: number;+}++export interface SmootherOptions {+ smoothing?: number;+ velocityWeight?: number;+ curvatureWeight?: number;+ minDistance?: number;+ maxPoints?: number;+ pressureSensitivity?: number;+ tiltSensitivity?: number;+ velocityThreshold?: number;+ samplingRate?: number;}export class FreehandSmoother {- private config: FreehandSmootherConfig;- private points: Point[];- private velocities: number[];-- constructor(options: Partial<FreehandSmootherConfig> = {}) {- // 默认配置- const defaultConfig: FreehandSmootherConfig = {- smoothing: 0.9, // 接近 1,最大平滑度- velocityWeight: 0.1, // 很小的速度影响,保持一致的平滑度- curvatureWeight: 0.1, // 很小的曲率影响,让转角也变得圆滑- maxPoints: 10, // 更多的历史点参与计算- minDistance: 1.0, // 强力过滤小幅度抖动- };+ private readonly defaultOptions: Required<SmootherOptions> = {+ smoothing: 0.65,+ velocityWeight: 0.2,+ curvatureWeight: 0.3,+ minDistance: 0.2, // 降低最小距离阈值+ maxPoints: 8,+ pressureSensitivity: 0.5,+ tiltSensitivity: 0.3,+ velocityThreshold: 800,+ samplingRate: 5, // 降低采样间隔+ };++ private options: Required<SmootherOptions>;+ private points: StrokePoint[] = [];+ private lastProcessedTime = 0;+ private movingAverageVelocity: number[] = [];+ private readonly velocityWindowSize = 3;++ constructor(options: SmootherOptions = {}) {+ this.options = { ...this.defaultOptions, ...options };+ }++ process(+ point: Point,+ data: Partial<Omit<StrokePoint, 'point'>> = {}+ ): Point | null {+ const timestamp = data.timestamp ?? Date.now();++ // 第一个点直接返回+ if (this.points.length === 0) {+ const strokePoint: StrokePoint = { point, timestamp, ...data };+ this.points.push(strokePoint);+ this.lastProcessedTime = timestamp;+ return point;+ }++ // 采样率控制 - 确保不会卡住+ if (timestamp - this.lastProcessedTime < this.options.samplingRate) {+ const timeDiff = timestamp - this.lastProcessedTime;+ if (timeDiff < 2) {+ // 如果时间间隔太小,跳过+ return null;+ }+ }- this.config = {- ...defaultConfig,- ...options,+ const strokePoint: StrokePoint = {+ point,+ timestamp,+ ...data,};+ // 距离检查 - 添加最小距离的动态调整+ const distanceOk = this.checkDistance(point);+ if (!distanceOk && this.points.length > 1) {+ // 如果距离太近,但时间间隔较大,仍然处理该点+ const timeDiff = timestamp - this.lastProcessedTime;+ if (timeDiff < 32) {+ // 32ms ≈ 30fps+ return null;+ }+ }++ // 更新历史点+ this.updatePoints(strokePoint);++ // 计算动态参数+ const dynamicParams = this.calculateDynamicParameters(strokePoint);++ // 应用平滑+ const smoothedPoint = this.smooth(point, dynamicParams);++ this.lastProcessedTime = timestamp;+ return smoothedPoint;+ }++ reset(): void {this.points = [];- this.velocities = [];+ this.lastProcessedTime = 0;+ this.movingAverageVelocity = [];}- public smoothPoint(point: Point): Point {+ private updatePoints(point: StrokePoint): void {this.points.push(point);- if (this.points.length > this.config.maxPoints) {+ if (this.points.length > this.options.maxPoints) {this.points.shift();}+ }- if (this.points.length < 2) return point;+ private checkDistance(point: Point): boolean {+ if (this.points.length === 0) return true;- // 计算速度- const velocity = this.calculateVelocity(point);- this.velocities.push(velocity);- if (this.velocities.length > this.config.maxPoints) {- this.velocities.shift();+ const lastPoint = this.points[this.points.length - 1].point;+ const distance = this.getDistance(lastPoint, point);++ // 动态最小距离:根据当前速度调整+ let minDistance = this.options.minDistance;+ if (this.movingAverageVelocity.length > 0) {+ const avgVelocity = this.getAverageVelocity();+ minDistance *= Math.max(0.5, Math.min(1.5, avgVelocity / 200));}- // 计算曲率- const curvature = this.calculateCurvature();+ return distance >= minDistance;+ }++ private calculateDynamicParameters(strokePoint: StrokePoint) {+ const velocity = this.calculateVelocity(strokePoint);+ this.updateMovingAverage(velocity);+ const avgVelocity = this.getAverageVelocity();- // 动态调整平滑系数- const adaptiveSmoothing = this.getAdaptiveSmoothing(velocity, curvature);+ const params = { ...this.options };- let smoothX = point[0];- let smoothY = point[1];- let totalWeight = 1;- let weight = 1;+ // 压力适应 - 更温和的压力响应+ if (strokePoint.pressure !== undefined) {+ const pressureWeight = Math.pow(strokePoint.pressure, 1.2);+ params.smoothing *= 1 - pressureWeight * params.pressureSensitivity * 0.8;+ }- // 指数加权移动平均- for (let i = this.points.length - 2; i >= 0; i--) {- weight *= adaptiveSmoothing;- totalWeight += weight;+ // 速度适应 - 更平滑的过渡+ const velocityFactor = Math.min(avgVelocity / params.velocityThreshold, 1);+ params.velocityWeight = 0.2 + velocityFactor * 0.3;+ params.smoothing *= 1 + velocityFactor * 0.2;- smoothX += this.points[i][0] * weight;- smoothY += this.points[i][1] * weight;+ // 倾斜适应 - 更温和的响应+ if (strokePoint.tiltX !== undefined && strokePoint.tiltY !== undefined) {+ const tiltFactor =+ Math.sqrt(strokePoint.tiltX ** 2 + strokePoint.tiltY ** 2) / 90;+ params.smoothing *= 1 + tiltFactor * params.tiltSensitivity * 0.7;}- return [smoothX / totalWeight, smoothY / totalWeight];+ return params;}- private calculateVelocity(point: Point): number {- if (this.points.length < 2) return 0;+ private smooth(point: Point, params: Required<SmootherOptions>): Point {+ if (this.points.length < 2) return point;++ const weights = this.calculateWeights(params);+ const totalWeight = weights.reduce((sum, w) => sum + w, 0);- const prev = this.points[this.points.length - 2];- const dx = point[0] - prev[0];- const dy = point[1] - prev[1];- const dt = 1; // 假设时间间隔恒定+ if (totalWeight === 0) return point;- return Math.sqrt(dx * dx + dy * dy) / dt;+ const smoothedPoint: Point = [0, 0];+ for (let i = 0; i < this.points.length; i++) {+ const weight = weights[i] / totalWeight;+ smoothedPoint[0] += this.points[i].point[0] * weight;+ smoothedPoint[1] += this.points[i].point[1] * weight;+ }++ return smoothedPoint;}- private calculateCurvature(): number {- if (this.points.length < 3) return 0;+ private calculateWeights(params: Required<SmootherOptions>): number[] {+ const weights: number[] = [];+ const lastIndex = this.points.length - 1;- const p1 = this.points[this.points.length - 3];- const p2 = this.points[this.points.length - 2];- const p3 = this.points[this.points.length - 1];+ for (let i = 0; i < this.points.length; i++) {+ // 基础权重 - 使用更温和的衰减+ let weight = Math.pow(params.smoothing, (lastIndex - i) * 0.8);- // 使用三点法计算曲率- const dx1 = p2[0] - p1[0];- const dy1 = p2[1] - p1[1];- const dx2 = p3[0] - p2[0];- const dy2 = p3[1] - p2[1];+ // 速度权重 - 更平滑的过渡+ if (i < lastIndex) {+ const velocity = this.getPointVelocity(i);+ weight *= 1 + velocity * params.velocityWeight * 0.8;+ }- // 使用叉积估算曲率- const cross = dx1 * dy2 - dy1 * dx2;- const velocity = Math.sqrt(dx1 * dx1 + dy1 * dy1);+ // 曲率权重 - 更温和的影响+ if (i > 0 && i < lastIndex) {+ const curvature = this.getPointCurvature(i);+ weight *= 1 + curvature * params.curvatureWeight * 0.7;+ }- return Math.abs(cross) / (velocity * velocity + this.config.minDistance);+ weights.push(weight);+ }++ return weights;}- private getAdaptiveSmoothing(velocity: number, curvature: number): number {- // 基于速度和曲率动态调整平滑系数- const velocityFactor = Math.exp(-velocity * this.config.velocityWeight);- const curvatureFactor = Math.exp(-curvature * this.config.curvatureWeight);+ // 工具方法保持不变+ private getDistance(p1: Point, p2: Point): number {+ return distanceBetweenPointAndPoint(p1[0], p1[1], p2[0], p2[1]);+ }- // 结合基础平滑系数和动态因子- return this.config.smoothing * velocityFactor * curvatureFactor;+ private calculateVelocity(point: StrokePoint): number {+ if (this.points.length < 2) return 0;++ const prevPoint = this.points[this.points.length - 1];+ const distance = this.getDistance(prevPoint.point, point.point);+ const timeDiff = point.timestamp - prevPoint.timestamp;+ return timeDiff > 0 ? distance / timeDiff : 0;}- // 获取当前配置- public getConfig(): FreehandSmootherConfig {- return { ...this.config };+ private updateMovingAverage(velocity: number): void {+ this.movingAverageVelocity.push(velocity);+ if (this.movingAverageVelocity.length > this.velocityWindowSize) {+ this.movingAverageVelocity.shift();+ }}- // 更新配置- public updateConfig(newConfig: Partial<FreehandSmootherConfig>): void {- this.config = {- ...this.config,- ...newConfig,- };+ private getAverageVelocity(): number {+ if (this.movingAverageVelocity.length === 0) return 0;+ return (+ this.movingAverageVelocity.reduce((a, b) => a + b) /+ this.movingAverageVelocity.length+ );}- // 重置状态- public reset(): void {- this.points = [];- this.velocities = [];+ private getPointVelocity(index: number): number {+ if (index >= this.points.length - 1) return 0;++ const p1 = this.points[index];+ const p2 = this.points[index + 1];+ const distance = this.getDistance(p1.point, p2.point);+ const timeDiff = p2.timestamp - p1.timestamp;+ return timeDiff > 0 ? distance / timeDiff : 0;}- // 获取当前点的数量- public getPointCount(): number {- return this.points.length;+ private getPointCurvature(index: number): number {+ if (index <= 0 || index >= this.points.length - 1) return 0;++ const p1 = this.points[index - 1].point;+ const p2 = this.points[index].point;+ const p3 = this.points[index + 1].point;++ const a = this.getDistance(p1, p2);+ const b = this.getDistance(p2, p3);+ const c = this.getDistance(p1, p3);++ const s = (a + b + c) / 2;+ const area = Math.sqrt(Math.max(0, s * (s - a) * (s - b) * (s - c)));+ return (4 * area) / (a * b * c + 0.0001); // 避免除零}}diff --git a/packages/drawnix/src/plugins/freehand/with-freehand-create.ts b/packages/drawnix/src/plugins/freehand/with-freehand-create.tsindex 3c55a68..dca841f 100644--- a/packages/drawnix/src/plugins/freehand/with-freehand-create.ts+++ b/packages/drawnix/src/plugins/freehand/with-freehand-create.ts@@ -20,7 +20,10 @@ export const withFreehandCreate = (board: PlaitBoard) => {const generator = new FreehandGenerator(board);- const smoother = new FreehandSmoother();+ const smoother = new FreehandSmoother({+ smoothing: 0.7,+ pressureSensitivity: 0.6,+ });let temporaryElement: Freehand | null = null;@@ -45,7 +48,7 @@ export const withFreehandCreate = (board: PlaitBoard) => {if (isFreehandPointer && isDrawingMode(board)) {isDrawing = true;const originPoint: Point = [event.x, event.y];- const smoothingPoint = smoother.smoothPoint(originPoint);+ const smoothingPoint = smoother.process(originPoint) as Point;const point = toViewBoxPoint(board,toHostPoint(board, smoothingPoint[0], smoothingPoint[1])@@ -58,19 +61,21 @@ export const withFreehandCreate = (board: PlaitBoard) => {board.pointerMove = (event: PointerEvent) => {if (isDrawing) {const originPoint: Point = [event.x, event.y];- const smoothingPoint = smoother.smoothPoint(originPoint);- generator?.destroy();- const newPoint = toViewBoxPoint(- board,- toHostPoint(board, smoothingPoint[0], smoothingPoint[1])- );- points.push(newPoint);- const pointer = PlaitBoard.getPointer(board) as FreehandShape;- temporaryElement = createFreehandElement(pointer, points);- generator.processDrawing(- temporaryElement,- PlaitBoard.getElementActiveHost(board)- );+ const smoothingPoint = smoother.process(originPoint);+ if (smoothingPoint) {+ generator?.destroy();+ const newPoint = toViewBoxPoint(+ board,+ toHostPoint(board, smoothingPoint[0], smoothingPoint[1])+ );+ points.push(newPoint);+ const pointer = PlaitBoard.getPointer(board) as FreehandShape;+ temporaryElement = createFreehandElement(pointer, points);+ generator.processDrawing(+ temporaryElement,+ PlaitBoard.getElementActiveHost(board)+ );+ }return;}