Using the custom SimpleGraph class from flashandmath.com

This page will show how to add a trace feature to the previous example. This allows us to highlight some additional features of the SimpleGraph and GraphingBoard classes. Even though the GraphingBoard object has a built-in cursor feature (add link to article here), our example shows how we can add functionality to a SimpleGraph object..

The example

You should click on the applet so it will have "focus" required for the arrow keys to function.

The code

import flashandmath.as3.tools.SimpleGraph;

txtXmin.tabIndex = 1;

txtXmax.tabIndex = 2;

txtYmin.tabIndex = 3;

txtYmax.tabIndex = 4;

txtFun.tabIndex = 5;

var numPoints:int = 400;

 

var g:SimpleGraph = new SimpleGraph(400,300);

g.x = 10;

g.y = 30;

addChild(g);

g.board.disableCoordsDisp();

 

var shCursor:Shape = new Shape();

shCursor.x = 0;

shCursor.y = 0;

g.addChildToBoard(shCursor);

 

var dTrace:Number = 2;

var traceX:Number = 0;

 

stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);

 

function keyPressed(kevt:KeyboardEvent):void {

if (kevt.keyCode == Keyboard.ENTER) {

drawGraph();

}

if (kevt.keyCode == Keyboard.LEFT) {

dTrace = -Math.abs(dTrace);

updateCursor();

}

if (kevt.keyCode == Keyboard.RIGHT) {

dTrace = Math.abs(dTrace);

updateCursor();

}

}

 

function drawGraph():void {

g.setWindow(txtXmin.text, txtXmax.text, txtYmin.text, txtYmax.text);

if (g.hasError()) {

shCursor.visible = false;

return;

}

g.graphRectangular(txtFun.text,"x",1,2,0x0000CC);

if (g.hasError()) {

shCursor.visible = false;

return;

}

g.board.drawAxes();

g.board.drawTicks();

g.board.drawGrid();

g.board.addLabels();

txtCoords.text = "";

updateCursor();

}

 

function updateCursor():void {

var realX, realY:Number;

if (g.hasError()) {

shCursor.visible = false;

return;

}

shCursor.visible = true;

traceX += dTrace;

if (traceX > (numPoints - 1)) {

traceX = numPoints - 1;

}

if (traceX < 0) {

traceX = 0;

}

realX = g.board.xfromPix(traceX);

realY = g.rectangularValueAt(1, realX );

 

shCursor.graphics.clear();

shCursor.graphics.lineStyle(2,0xAA0000);

shCursor.graphics.moveTo(0,g.board.ytoPix( realY ) );

shCursor.graphics.lineTo(bWidth, g.board.ytoPix( realY ) );

shCursor.graphics.moveTo(traceX, 0);

shCursor.graphics.lineTo(traceX, bHeight);

 

txtCoords.text = "(" + realX.toFixed(2) + ", " + realY.toFixed(2) + ")";

}

 

drawGraph();

Download

Download both fla files for this tutorial, along with the folder of class files and their documentation, in the following compressed folder.

Back to Basic Tutorials              Back to Flash and Math Home

We welcome your comments, suggestions, and contributions. To contact us, email Barbara Kaskosz at barbara@flashandmath.com, Doug Ensley at doug@flashandmath.com, or Dan Gries at dan@flashandmath.com.

Adobe®, Flash®, Flex® are registered trademarks of Adobe Systems Incorporated.