2) Javascript has this great method to evaluate an expression (for other compiled langauge, that is quite hard to do)
var x = 10; var expression = "2*x+3" alert(eval(expression))See it in action.
Give yourself a function to evaluate
function func(x) {
var eq=document.getElementById("func").value;
var result= eval("x="+x+";"+eq);
return result;
}
3) Figure out your coordinates
The function plotter has (-5,-5) to (5,5) in range. This is called your world coordinate.
Your plotting canvas is going from (0,0) to (500,500) in range. That is called the view coordinate.
You will need to do some transformation.
var xvl = 0; var yvl = 0; // viewport is the Canvas var xvu = 500 var yvu = 500 var xwl = -5 var ywl = -5 var xwu = 5 var ywu = 5 var Sx = (xvu - xvl) / (xwu - xwl); var Sy = (yvu - yvl) / (ywu - ywl); var Tx = (xwu * xvl - xwl * xvu) / (xwu - xwl); var Ty = (ywu * yvl - ywl * yvu) / (ywu - ywl);4) Give yourself a convenience function to plot line
function plotLine2D(context, x1, y1, x2, y2, c) {
t_x1 = Sx * x1 + Tx;
t_y1 = 500- (Sy * y1 + Ty);
t_x2 = Sx * x2 + Tx;
t_y2 = 500 -(Sy * y2 + Ty);
if (c=="blue") context.strokeStyle = "#00f"
if (c=="black") context.strokeStyle = "#000"
context.lineWidth = 2;
context.beginPath();
context.moveTo(t_x1, t_y1);
context.lineTo(t_x2, t_y2);
context.stroke();
context.closePath();
}
5) Give yourself another convenience function to clear screen (with a black border)
function cls(context) {
context.fillStyle = '#fff';
context.strokeStyle = '#f00';
context.beginPath();
context.moveTo(0,0);
context.lineTo(0,500);
context.lineTo(500,500);
context.lineTo(500,0);
context.fill();
context.closePath();
}
Now, all you have to do is
1) Plot axes:
var xmin = xwl; var ymin = ywl; var xmax = xwu; var ymax = ywu; plotLine2D(context, xmin, 0, xmax, 0, "black"); // x-axis; plotLine2D(context, 0, ymin, 0, ymax, "black"); // y-axis;2) Plot little ticks
var tick = 1
for (x = xmin; x <= xmax; x += tick) {
plotLine2D(context,x, -0.1, x, 0.1, "black");
}
for (y = ymin; y <= ymax; y += tick) {
plotLine2D(context,-0.1, y, 0.1, y, "black");
}
3) do a loop to plot 100 little segments.
var dx = (xmax - xmin) / 100;
var x, y, oldx, oldy;
var hasError = false
x = xmin;
y = func(x);
oldx = x;
oldy = y;
while (x <= xmax) {
x = x + dx;
y = func(x);
plotLine2D(context, oldx, oldy, x, y, "blue");
oldx = x;
oldy = y;
}// while
Ok just copy everything here. View Source look for [BEGIN]
This is my first Android App but unfortunately not many is willing to pay just $1. (Too many people made free ones that are better)