Over the past two weeks I've taught two different lessons covering the basic ins and outs of the Graphics class (Drawing API). Something I noticed is that it's not always immediately apparent when you're starting out that the clear() method can be used to animate dynamically drawn vector graphics. That is, in both my class demos I introduced clear() by using it to erase a canvas when a button was clicked. When I described the idea of continuously clearing and redrawing graphics to create an animation there was some confusion, so I created a simple demo on the fly:
addEventListener(Event.ENTER_FRAME, onLoop, false, 0, true);
function onLoop(evt:Event):void {
graphics.clear();
graphics.lineStyle(1,0x000000);
graphics.moveTo(100,100);
graphics.lineTo(mouseX, mouseY);
}
Copy this into your timeline if you're not sure what it does.
I then showed examples from the web where people were using the Graphics class clear() method for more interesting things than just drawing a simple line, and I thought I'd create another example for future lessons:
Here's the code, which can be placed in a timeline frame script:
-
var points:Array = new Array();
-
var pointNum:int = 100;
-
var canvas:Sprite = new Sprite();
-
addChild(canvas);
-
-
for (var i:int = 0; i<pointNum; i++) {
-
points.push(new Point(100,100+i));
-
}
-
-
addEventListener(Event.ENTER_FRAME, onLoop, false, 0, true);
-
-
function onLoop(evt:Event):void {
-
canvas.graphics.clear();
-
canvas.graphics.lineStyle(10,0);
-
points[0].x = mouseX;
-
points[0].y = mouseY;
-
canvas.graphics.moveTo(points[0].x, points[0].y);
-
for (var i:int = 1; i <pointNum; i++) {
-
points[i].x += (points[i-1].x - points[i].x) / 2;
-
points[i].y += ((points[i-1].y) + 1 - points[i].y) / 2;
-
canvas.graphics.lineTo(points[i].x, points[i].y);
-
}
-
}
In this demo there is an array of 100 points. On enter frame, points[0] is set to the mouse location. A for loop is then used so that point[1] follows point[0], point[2] follows point[1], etc. All the y values are offset by one pixel to create the vertical scrolling effect.
Print This Post


(5 votes, average: 4.6 out of 5) 






























Thanx
This is great! thanks for the post as I love action script and never thought to use " clear " in this manor! GREAT POST!!