steveruizok / perfect-freehand

Draw perfect pressure-sensitive freehand lines.
https://perfectfreehand.com
MIT License
4.48k stars 156 forks source link

Fix lines with one point #22

Closed steveruizok closed 3 years ago

steveruizok commented 3 years ago

This PR fixes a bug where lines with only one point were causing arrays with NaN values.

https://github.com/steveruizok/perfect-freehand/issues/19

If the library detects a line with only one point, it pushes a second point onto the line with a tiny offset. The bug here was that we were failing to update a variable named len that stores the length of the input points, and which was used to iterate over the points.

  let len = pts.length

  if (len === 1) pts.push(vec.add(pts[0], [1, 0]))

  const strokePoints: StrokePoint[] = [{ ... }]

  for (
    let i = 1, j = 0, curr = pts[i], prev = strokePoints[j];
    i < len; // <---------------------- Would still be 1, but it should be 2!
    i++, curr = pts[i], prev = strokePoints[j]
  ) {
    const point = vec.lrp(prev.point, curr, 1 - streamline)

This is now fixed.

Note

Even though the library won't produce a bad line here, you may want to treat lines with only one point differently. For example, in tldraw.com, I don't render lines with only one point; and if the lines have a length of two, then I render a circle instead of a stroke path. Short lines are this lib's white whale, very hard to get right. πŸ‹

vercel[bot] commented 3 years ago

This pull request is being automatically deployed with Vercel (learn more).
To see the status of your deployment, click below or on the icon next to each commit.

πŸ” Inspect: https://vercel.com/steveruiz/perfect-freehand-example/6ZeVXzUn9fkGEN4X98UayJfaVcG5
βœ… Preview: https://perfect-freehand-example-git-fix-lines-with-one-point-steveruiz.vercel.app