Actionscript:
-
var canvas:BitmapData = new BitmapData(400,400,false, 0x000000);
-
addChild(new Bitmap(canvas));
-
var pnts:Array = new Array();
-
// make 8 control points
-
for (var i:int = 0; i<8; i++){
-
pnts.push(dot(50 + i * (30 + Math.random()*10),
-
50 + i * (30 + Math.random()*10)));
-
}
-
addEventListener(Event.ENTER_FRAME, onLoop);
-
function onLoop(evt:Event):void {
-
canvas.lock();
-
canvas.fillRect(canvas.rect, 0x000000);
-
curve(pnts);
-
canvas.unlock();
-
}
-
function tangent(pk1:Sprite, pk_1:Sprite){
-
return new Point((pk1.x - pk_1.x) / 2, (pk1.y - pk_1.y) / 2);
-
}
-
// all math from http://en.wikipedia.org/wiki/Cubic_Hermite_spline
-
function curve(p:Array, res:Number=.03):void{
-
var px:Number = 0;
-
var py:Number = 0;
-
var pIter:int = p.length - 1;
-
var m:Array = [];
-
m[0] = tangent(p[1], p[0]);
-
for (var i:int = 1; i<pIter; i++){
-
m[i] = tangent(p[i + 1], p[i - 1]);
-
}
-
m[pIter] = tangent(p[pIter], p[pIter - 1]);
-
for (var t:Number = 0; t <1; t+=res){
-
var t_2:Number = t * t;
-
var _1_t:Number = 1 - t;
-
var _2t:Number = 2 * t;
-
var h00:Number = (1 + _2t) * (_1_t) * (_1_t);
-
var h10:Number = t * (_1_t) * (_1_t);
-
var h01:Number = t_2 * (3 - _2t);
-
var h11:Number = t_2 * (t - 1);
-
for (var k:int = 0; k <pIter; k++){
-
var k1:int = k + 1;
-
var pk:Sprite = p[k];
-
var pk1:Sprite = p[k1];
-
var mk:Point = m[k];
-
var mk1:Point = m[k1];
-
px = h00 * pk.x + h10 * mk.x + h01 * pk1.x + h11 * mk1.x;
-
py = h00 * pk.y + h10 * mk.y + h01 * pk1.y + h11 * mk1.y;
-
canvas.setPixel(px, py, 0xFFFFFF);
-
}
-
}
-
}
-
// draggable dot
-
function dot(xp:Number, yp:Number, col:uint = 0xFF0000, rad:Number=4):Sprite {
-
var s:Sprite = Sprite(addChild(new Sprite));
-
s.x = xp;
-
s.y = yp;
-
with(s.graphics) beginFill(col), drawCircle(0,0,rad);
-
s.buttonMode = true;
-
s.addEventListener(MouseEvent.MOUSE_DOWN, onDrag);
-
return s;
-
}
-
function onDrag(evt:MouseEvent):void {
-
evt.currentTarget.startDrag()
-
}
-
stage.addEventListener(MouseEvent.MOUSE_UP, onUp);
-
function onUp(evt:MouseEvent):void{
-
stopDrag();
-
}
More Catmull-Rom stuff. This one can have any number of control points: