Cheap way of calculating cubic bezier length

后端 未结 6 2045
遇见更好的自我
遇见更好的自我 2021-02-04 03:12

An analytical solution for cubic bezier length seems not to exist, but it does not mean that coding a cheap solution does not exist. By cheap I mean something like in the rang

6条回答
  •  别跟我提以往
    2021-02-04 03:33

    Simplest algorithm: flatten the curve and tally euclidean distance. As long as you want an approximate arc length, this solution is fast and cheap. Given your curve's coordinate LUT—you're talking about speed, so I'm assuming you use those, and don't constantly recompute the coordinates—it's a simple for loop with a tally. In generic code, with a dist function that computes the euclidean distance between two points:

    var arclength = 0,
        last=LUT.length-1,
        i;
    for (i=0; i

    Done. arclength is now the approximate arc length based on the maximum number of segments you can form in the curve based on your LUT. Need things faster with a larger potential error? Control the segment count.

    var arclength = 0,
        segCount = ...,
        last=LUT.length-2,
        step = last/segCount,
        s, i;
    for (s=0; s<=segCount; s++) {
      i = (s*step/last)|0;
      arclength += dist(LUT[i], LUT[i+1]);
    }
    

    This is pretty much the simplest possible algorithm that still generates values that come even close to the true arc length. For anything better, you're going to have to use more expensive numerical approaches (like the Legendre-Gauss quadrature technique).

    If you want to know why, hit up the arc length section of "A Primer on Bézier Curves".

提交回复
热议问题