瀏覽代碼

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

Gasim Gasimzada 5 年之前
父節點
當前提交
b09373acf7
共有 1 個文件被更改,包括 42 次插入6 次删除
  1. 42 6
      src/element/bounds.ts

+ 42 - 6
src/element/bounds.ts

@@ -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 size = 30; // pixels
+  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 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);