Bézier Curves

David's picture

I was working with bézier curves the other day for a flash animation and need a way to compute points along the curve. It is very easy to draw a bézier curve in actionscript with two lines of code.

this.graphics.moveTo(p1x, p1y);
this.graphics.curveTo(cx, cy, p2x, p2y);

The first line simply sets (x, y) location of the starting point. The second line actually draws the curve by specifying the end point (p2x, p2y) and the curve control point (cx, cy). By using a little math we can calculate points along the curve. Here is a good resouce that covers the math and has some code that I repurposed. In general we need those three points we defined and T which is a value between 0 and 1. Below is a quick script that draws a curve and draws boxes along the curve at interval T. It is very simple but I have to give most of the credit to Antoine Leclair and his blog entry.

package {
	import flash.display.MovieClip;
	import flash.display.Graphics;
	import flash.display.Shape;
	public class beizer extends MovieClip {

		public function beizer() {
			this.graphics.lineStyle(1, 0x990000, .75);
			var t:Number = 0;
			var p1x:Number = 100;
			var p1y:Number = 100;
			var cx:Number = 50;
			var cy:Number = 500;
			var p2x:Number = 500;
			var p2y:Number = 500;
			this.graphics.moveTo(p1x, p1y); 
			this.graphics.curveTo(cx, cy, p2x, p2y);
			for( t = 0; t <= 1; t +=0.05){
				var c1x:Number = p1x + (cx - p1x) * t;
				var c1y:Number = p1y + (cy - p1y) * t;
				var c2x:Number = cx + (p2x - cx) * t;
				var c2y:Number = cy + (p2y - cy) * t;
				var tx:Number = c1x + (c2x - c1x) * t;
				var ty:Number = c1y + (c2y - c1y) * t;
				this.graphics.drawRect(tx -5, ty -5 , 10, 10);


Also you can download all the souce code here so you can play with it in Flash.