Skip to content

Commit

Permalink
feat: add smooth to demo
Browse files Browse the repository at this point in the history
  • Loading branch information
NateScarlet committed Aug 17, 2019
1 parent f051da8 commit a5e084e
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 3 deletions.
10 changes: 7 additions & 3 deletions demo/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as svgVariableWidthLine from '@';
import { Point } from '@';

class DrawingHandler {
public el: SVGSVGElement;
Expand Down Expand Up @@ -37,8 +38,9 @@ class DrawingHandler {
return;
}
this.lastDrawTime = Date.now();
const p = svgVariableWidthLine.util.translatePoint(this.el, e);
p.w = e.pressure * this.width;
const { x, y } = svgVariableWidthLine.util.translatePoint(this.el, e);
const w = e.pressure * this.width;
const p: Point = { x, y, w };
const lastPoint = this.points.slice(-1)[0];
if (
lastPoint &&
Expand All @@ -60,7 +62,9 @@ class DrawingHandler {
this.el.addEventListener('pointerup', this.onPointerup.bind(this));
}
update(): void {
const { d } = svgVariableWidthLine.compute(...this.points);
const { d } = svgVariableWidthLine.compute(
...svgVariableWidthLine.smooth(this.points, 4)
);
this.mustTarget.setAttribute('d', d);
}
}
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ import * as vector2 from './vector2';
export * from './compute';
export * from './types';
export { util, vector2 };
export * from './smooth';
40 changes: 40 additions & 0 deletions src/smooth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { Point } from './types';

// Refer: https://github.com/Jam3/chaikin-smooth/blob/master/index.js

export function smoothOnce(...points: Point[]): Point[] {
const ret: Point[] = [];
if (points.length === 0) {
return [];
}
ret.push({ ...points[0] });
for (let i = 0; i < points.length - 1; i++) {
const p0 = points[i];
const p1 = points[i + 1];

ret.push(
{
x: 0.75 * p0.x + 0.25 * p1.x,
y: 0.75 * p0.y + 0.25 * p1.y,
w: p0.w * 0.75 + p1.w * 0.25,
},
{
x: 0.25 * p0.x + 0.75 * p1.x,
y: 0.25 * p0.y + 0.75 * p1.y,
w: p0.w * 0.25 + p1.w * 0.75,
}
);
}
if (points.length > 2) {
ret.push({ ...points[points.length - 1] });
}
return ret;
}

export function smooth(points: Point[], times = 1): Point[] {
let ret = points;
for (let count = 0; count < times; count += 1) {
ret = smoothOnce(...ret);
}
return ret;
}

0 comments on commit a5e084e

Please sign in to comment.