plot

by mikot

HTML

<head>
 <link rel="stylesheet" type="text/css" href="http://jsxgraph.uni-bayreuth.de/distrib/jsxgraph.css" />
 <script type="text/javascript" charset="UTF-8" src="//cdnjs.cloudflare.com/ajax/libs/jsxgraph/0.99.3/jsxgraphcore.js"></script>
</head>

<body>
<div id="jsxbox" class="jxgbox" style="width:400px; height:400px; border:3px; border-style:solid;"></div>
  
<input id="function" type="text" name="function"><input id="plot" type="button" value="plot" />
</body>

JavaScript

var board	=	JXG.JSXGraph.initBoard('jsxbox', {axis:1, grid:0, keepaspectratio:1, shownavigation:0, showcopyright:0, pan:{enabled:0}, boundingbox:[-15, 15, 15, -15]});
      var graph;
      
      function update(){
        var input = parseInput(document.getElementById("function").value);
        board.removeObject(graph);
        graph = board.create('functiongraph', [function(x){ return eval(input); },-15,15], {strokeWidth:2});
        board.update();
      }

      function parseInput(input){
        var temp = input, buffer = "";
          /*monomials*/
          var i = 0;
          while(i < temp.length){
            var next = temp.charAt(i);
            if(temp.charAt(i) == "x" && temp.charAt(i+1) == "^"){
              buffer += "Math.pow(x," + temp.charAt(i+2) + ")";
              i = i+3;
            }else if(isNaN(next)){

                if(next != "/" && next != "*" && next != "("  && next != ")" && next != "-"  && next != "+" && 										next != "x"){
                    
                  buffer += "Math.";

                  while(isNaN(temp.charAt(i))){
                    next  = temp.charAt(i);
                    buffer += next;
                    i++;

                    if(next == ")"){
                      break;
                    }
                  }
                }else{
                    buffer += next;
                    i++;
                }
                  
            }else {
              buffer += next;
              i++;
            }
          }
          /*board.create('text',[5,5,buffer]);*/
          return buffer;
      }
      
      document.getElementById("plot").onclick = update;