Align arrow caps based on bezier curve instead of stored points (#737)

This commit is contained in:
Gasim Gasimzada 2020-02-09 17:23:09 +04:00 committed by GitHub
parent c2a3b67ccc
commit b09373acf7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -119,12 +119,48 @@ export function getLinearElementAbsoluteBounds(element: ExcalidrawElement) {
}
export function getArrowPoints(element: ExcalidrawElement) {
const points = element.points;
const [x1, y1] = points.length >= 2 ? points[points.length - 2] : [0, 0];
const [x2, y2] = points[points.length - 1];
const shape = element.shape as Drawable[];
const ops = shape[0].sets[0].ops;
const data = ops[ops.length - 1].data;
const p3 = [data[4], data[5]] as Point;
const p2 = [data[2], data[3]] as Point;
const p1 = [data[0], data[1]] as Point;
// we need to find p0 of the bezier curve
// it is typically the last point of the previous
// curve; it can also be the position of moveTo operation
const prevOp = ops[ops.length - 2];
let p0: Point = [0, 0];
if (prevOp.op === "move") {
p0 = prevOp.data as Point;
} else if (prevOp.op === "bcurveTo") {
p0 = [prevOp.data[4], prevOp.data[5]];
}
// B(t) = p0 * (1-t)^3 + 3p1 * t * (1-t)^2 + 3p2 * t^2 * (1-t) + p3 * t^3
const equation = (t: number, idx: number) =>
Math.pow(1 - t, 3) * p3[idx] +
3 * t * Math.pow(1 - t, 2) * p2[idx] +
3 * Math.pow(t, 2) * (1 - t) * p1[idx] +
p0[idx] * Math.pow(t, 3);
// we know the last point of the arrow
const [x2, y2] = p3;
// by using cubic bezier equation (B(t)) and the given parameters,
// we calculate a point that is closer to the last point
// The value 0.3 is chosen arbitrarily and it works best for all
// the tested cases
const [x1, y1] = [equation(0.3, 0), equation(0.3, 1)];
// find the normalized direction vector based on the
// previously calculated points
const distance = Math.hypot(x2 - x1, y2 - y1);
const nx = (x2 - x1) / distance;
const ny = (y2 - y1) / distance;
const size = 30; // pixels
const distance = Math.hypot(x2 - x1, y2 - y1);
const arrowLength = element.points.reduce((total, [cx, cy], idx, points) => {
const [px, py] = idx > 0 ? points[idx - 1] : [0, 0];
return total + Math.hypot(cx - px, cy - py);
@ -134,8 +170,8 @@ export function getArrowPoints(element: ExcalidrawElement) {
// This value is selected by minizing a minmum size with the whole length of the arrow
// intead of last segment of the arrow
const minSize = Math.min(size, arrowLength / 2);
const xs = x2 - ((x2 - x1) / distance) * minSize;
const ys = y2 - ((y2 - y1) / distance) * minSize;
const xs = x2 - nx * minSize;
const ys = y2 - ny * minSize;
const angle = 20; // degrees
const [x3, y3] = rotate(xs, ys, x2, y2, (-angle * Math.PI) / 180);