Swirl Gradient

var canvas:BitmapData=new BitmapData(200,200,false,0x000000);
addChild(new Bitmap(canvas));
scaleX=scaleY=2;
var pixNum:int=canvas.width*canvas.height;

var xp:Vector.<int> = new Vector.<int>();
var yp:Vector.<int> = new Vector.<int>();
var radius:Vector.<Number> = new Vector.<Number>();
var theta:Vector.<Number> = new Vector.<Number>();
for (var i:int = 0; i<pixNum; i++) {
	xp.push(i % 200);
	yp.push(int(i / 200));
	var dx:Number=100-xp[i];
	var dy:Number=100-yp[i];
	theta.push(Math.atan2(dy, dx));
	radius.push(Math.sqrt(dx * dx + dy * dy)/20);
}

addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
	canvas.lock();
	var n:Number = mouseX / 100;
	for (var i:int = 0; i<pixNum; i++) {
		var swirl:Number = 1+Math.sin(6*Math.cos(radius[i]) -n*theta[i]);
		canvas.setPixel(xp[i], yp[i],  Math.abs(255 - swirl * 255));
	}
	canvas.unlock();
}

This snippet creates a swirl gradient. While this snippet is not highly optimized, it does implement a basic optimization technique … I cache some repetitive calculations in Vectors and then use them on the main loop.

I got the function for a swirl gradient from mathworld…

Leave a Reply

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