ActionScript Bezier Curves (Cartogrammar)

[Editor’s note: For those programmers in AS3 wanting to draw pretty curves ala Postscript, PDF, or Illustrator.]

Republished from Cartogrammer. View comments there for updates.
January 5, 2009. Andy Woodruff.

[Andy] finally opened [his] CubicBezier AS3 class, the only reason anyone ever finds this site at all, for the first time in many months to attempt to address some of the various comments and reported problems from the original. It’s not perfected, but [he’s] done three things:

  1. Added a “moveTo” argument to the curveThroughPoints method, following the idea in one comment on my blog post. Ignore it if you wish, but if you set it to false, the curves will connect to wherever graphics drawing left off rather than moving to the beginning of the curve and starting anew.
  2. Hooray trigonometry! Messed with some of the angle calculations to fix problems with zero angles and division by zero. I hope it worked.
  3. Provided a line of code that can be altered to use lineTo for straight segments of 3 or more points rather than curving.

Straight lines were raised as an issue in several comments. While I think I have fixed the crazy behavior of straight horizontal and vertical lines, I suspect the result for three points in a line may be surprising at first glance. For instance, the three middle points in the image below are all aligned horizontally.

Straight line with S-curve

The S-curve through those points may look odd at first, but it’s actually to be expected with these cubic Bézier curves. Of those three points, only the middle one has curve control points that are also aligned horizontally. The outer two have control points that are also based on the points outside the line. Here’s an approximate example from Illustrator of what they look like

S-curve in Illustrator

I’ve left that as the default behavior, but I did insert some code that can be modified so that the curve essentially stops curving when it reaches several points in a line, draws a straight line through them, and then continues curving as normal after that. Here’s what the same example looks like with that option enabled.

Straight line with lineTo

It’s probably often fine, but I caution that it can result in sharp corners. Here’s the same with those dots removed:

Straight line with lineTo and sharp corners

I’m uncertain what’s best, so I’ve made that a line of code that has to be changed rather than a more accessible option. I’d be glad to hear ideas on how best to handle it. Feel free to change it however you like, of course. That and other modifications are identified in the comments.

Download the class here:
The previous version is here, in case I screwed something up. Forgive my lack of version control.

Tags: , , , , , , , , ,

Comments are closed.