Changing the function in the text box is not changing the graph

蓝咒 提交于 2019-12-12 02:23:50

问题


I am attempting to create a fiddle which can allow me to change the graph through and input text showing below the graph. I am using jsxgraph library for that.

http://jsxgraph.uni-bayreuth.de/wiki/index.php/Change_Equation_of_a_Graph#JavaScript_Part

Above is the example which is working when you change the function in the text shown graph also changes.

Same example I am trying with the fiddle. But it is not working.

https://jsfiddle.net/me55dw4h/30/

initial code:

board = JXG.JSXGraph.initBoard('box', {boundingbox: [-6, 12, 8, -6], axis: true});
eval("function f(x){ return "+document.getElementById("eingabe").value+";}");
graph = board.create('functiongraph', [function(x){ return f(x); },-10, 10]);

How do I make it work?


回答1:


This is a jsfiddle-specific problem. If the declaration of the function doIt is changed to

doIt = function (){
  //redefine function f according to the current text field value
  eval("function f(x){ return "+document.getElementById("eingabe").value+";}");
  //change the Y attribute of the graph to the new function 
  graph.Y = function(x){ return f(x); };
  //update the graph
  graph.updateCurve();
  //update the whole board
  board.update();
};

instead of

function doIt() {
     ...
}

then the example runs.

But let me emphasize that meanwhile JSXGraph comes with it's own parser JessieCode (see https://github.com/jsxgraph/JessieCode), which allows the input of common math syntax instead of JavaScript syntax. That means, instead of Math.sin(x) the user may just input sin(x). Additionally, there is the power operator ^, i.e. instead of Math.pow(x,2) it is possible to type x^2.

A minimal example using JessieCode for function plotting looks like this, see https://jsfiddle.net/eLs83cs6/

board = JXG.JSXGraph.initBoard('box', {boundingbox: [-6, 12, 8, -6], axis: true});

doPlot = function() {
    var txtraw = document.getElementById('input').value, // Read user input
        f = board.jc.snippet(txtraw, true, 'x', true), // Parse input with JessieCode
        curve;

    board.removeObject('f'); // Remove element with name f
    curve = board.create('functiongraph', [f, -10, 10], {name:'f'});
};

doPlot();

Ann additional side effect is that the parsing of the math syntax with JessieCode prevents XSS attacks which would be easily possible if the users are allowed to supply arbitrary JavaScript code as input.



来源:https://stackoverflow.com/questions/39761153/changing-the-function-in-the-text-box-is-not-changing-the-graph

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!