Drawing crazy lines with actionscript
In this flash actionscript tutorial we will play a bit more with the drawing api, this time we will apply some randomness to the drawing, so we will draw a line then will continue drawing by it self, using some random calculations.
You can see here what I came up with, and yes this is not really a graph for anything, its not my heart rhythm or anything, I just used the random math class and made up my own small math formula.
Now this is only a coding tutorial, so you will have no need to do anything with drawing, and making movie clips or anything, just jump right into the actionscript panel and start programming.
To make it easier to understand I have tried line by line to explain the code, you can see the code description inside the code, or you can just copy and paste the code into your own flash project and play around with it.
First we set a few variables, first two defines the start position of the line.
var oldX:Number = 30;
var oldY:Number = 150;
var randomX:Number;
var randomY:Number;
Now we define the line style we will draw with. 2 px thick and black color.
this.graphics.lineStyle(3,0x00BB00);
The start position
this.graphics.moveTo(oldX,oldY);
// now we add an eventlistener to draw the line, its an enterframe event, so it keeps repeating 12 frames per sec.
this.addEventListener(Event.ENTER_FRAME, drawRandom);
And here is the actural function.
function drawRandom(event:Event):void {
// this is the small calculations to tell flash what the line should draw, you can change it a round do more simple or more complicated calculations.
randomX = oldX + Math.random() * 3;
randomY = 50 + Math.tan(oldY + Math.random() * 3);
// and here we set it to draw the line, (finally).
this.graphics.lineTo(randomX,randomY);
oldX = randomX;
oldY = randomY;
}