setPixel() Cubic Bezier

var canvas:BitmapData=new BitmapData(280,280,false,0x000000);
addChild(new Bitmap(canvas, PixelSnapping.AUTO, true));

var color:uint;

// anchor x1, anchor y1, 
// control-handle x2, control-handle y2, 
// anchor x3, anchor y3, control-handle x4, 
// control-handle y4, [resolution incremental value between 0-1]
function cubicBezier(x1:Number, y1:Number, x2:Number, y2:Number, 
	                      x3:Number, y3:Number, x4:Number, y4:Number, resolution:Number=.03):void {
	
	var b:Number,pre1:Number,pre2:Number,pre3:Number,pre4:Number;
	for (var a = 0; a < 1; a+=resolution) {
		b=1-a;
		pre1=(a*a*a);
		pre2=3*(a*a)*b;
		pre3=3*a*(b*b);
		pre4=(b*b*b);
		canvas.setPixel(pre1*x1 + pre2*x2 + pre3*x4 + pre4*x3 ,
				         pre1*y1 + pre2*y2 + pre3*y4 + pre4*y3, color);
	}
}

// draw a few

color = 0xFFFFFF;

cubicBezier(100,100, 
                    150, 50, 
                    200, 100, 
                    150, 150);

color = 0xFF0000;

cubicBezier(10,10,
                    150, 10,
                    200, 200, 
                    250, 150,
			    .01);
/*
WARNING: This code was written for fun. Use at your own risk.
*/

This draws cubic bezier curves with setPixel. I’m pretty sure I picked up the original math from somewhere on the processing forums in ’03 or ’04…

Leave a Reply

Your email address will not be published. Required fields are marked *