I’m trying to write the base code for a graphing document that shows a value on the graph each time an int is pushed into an array. Here is the code-
import flash.display.Shape;
import flash.display.MovieClip;
import flash.display.Sprite;
var myShape:Shape = new Shape();
myShape.graphics.lineStyle(2, 0x990000, 2);
var max:Number = 0;
var graph:Array = new Array();
var container:Sprite = new Sprite();
var redrawGraph = setInterval(reDraw,1000);
function reDraw()
{
while (container.numChildren)
{
container.removeChildAt(0);
}
graph.push(randomNum());
graph.reverse();
for (var ints in graph)
{
if (graph[ints] > max)
{
max = graph[ints];
}
}
for (var i:Number = 0; i < graph.length-1; i++)
{
myShape.graphics.moveTo(550-i*50, (max – graph[i])*20);
myShape.graphics.lineTo(550-(i+1)*50, (max – graph[i+1])*20);
container.addChild(myShape);
}
this.addChild(container);
graph.reverse();
}
function randomNum():int
{
return Math.floor(Math.random() * 11);`
}
Except the issue i’m having is I end up with the graph overlapping the previous one, the part where it should be removing the old graph shapes doesn’t seem to be working…and I can’t figure out why.
Any help would be appreciated.
(sorry about the formatting…it wouldn’t work properly
You have a misunderstanding of the difference between display objects hierarchy and manipulating the
graphicsobject of a display object.You are using
setIntervalto call areDrawcallback.In the
reDrawcallback, you are usinggraphics.moveToandgraphics.lineToto draw your graph. However, every frame you are constantly drawing to the same “canvas”, the sameSprite:myShape.Adding and removing the display objects from each other is unnecessary. In this case, you only need to add the display objects once. And then on each refresh, clear the canvas and start drawing again.
For example, consider the following:
Here I am creating a the shape, putting the shape into the container, and then adding the container to the root display object, and thats pretty much it. And then…
Then here, notice that I am not removing or adding anything to the display tree, the tree is already organized the way that I want. All I’m doing on a redraw is clearing my shape, and then redrawing it the way that I want it to be displayed.
Sometimes you do need to manipulate the display hierarchy, but this is not one of those times.
See here for a working example…