Skip to content

Commit a2bb970

Browse files
committed
Internal lib - Add vertical smooth line utility function
1 parent 54d1da6 commit a2bb970

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

src/lib.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -779,6 +779,40 @@ export function createSmoothPath(points) {
779779
return path.join(' ');
780780
}
781781

782+
export function createSmoothPathVertical(points, smoothing = 0.2) {
783+
function line(pointA, pointB) {
784+
const lengthX = pointB.x - pointA.x;
785+
const lengthY = pointB.y - pointA.y;
786+
return {
787+
length: Math.sqrt(Math.pow(lengthX, 2) + Math.pow(lengthY, 2)),
788+
angle: Math.atan2(lengthY, lengthX)
789+
};
790+
}
791+
function controlPoint(current, previous, next, reverse) {
792+
const p = previous || current;
793+
const n = next || current;
794+
const o = line(p, n);
795+
796+
const angle = o.angle + (reverse ? Math.PI : 0);
797+
const length = o.length * smoothing;
798+
799+
const x = current.x + Math.cos(angle) * length;
800+
const y = current.y + Math.sin(angle) * length;
801+
return { x, y };
802+
}
803+
function bezierCommand(point, i, a) {
804+
const cps = controlPoint(a[i - 1], a[i - 2], point);
805+
const cpe = controlPoint(point, a[i - 1], a[i + 1], true);
806+
return `C ${checkNaN(cps.x)},${checkNaN(cps.y)} ${checkNaN(cpe.x)},${checkNaN(cpe.y)} ${checkNaN(point.x)},${checkNaN(point.y)}`;
807+
}
808+
const d = points.filter(p => !!p).reduce((acc, point, i, a) => i === 0
809+
? `${checkNaN(point.x)},${checkNaN(point.y)} `
810+
: `${acc} ${bezierCommand(point, i, a)} `
811+
, '');
812+
813+
return d;
814+
}
815+
782816

783817
export function createUid() {
784818
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
@@ -1941,6 +1975,7 @@ const lib = {
19411975
createPolarAreas,
19421976
createPolygonPath,
19431977
createSmoothPath,
1978+
createSmoothPathVertical,
19441979
createSpiralPath,
19451980
createStar,
19461981
createStraightPath,

0 commit comments

Comments
 (0)