JSXGraph - 持久性问题:绘制多个函数

JSXGraph - Persistency Problem : Drawing more than one function

我想使用 JSXGraph 代码在 for 循环中绘制多图。一切似乎都很好,工作但是当我点击一个点或一条切线时,它们都消失了,因为它们在 for 循环下。我的理解是,我需要像 Java 那样将它们放入绘画函数中(并在某处更新),但我无法成功找到它。使用 for 循环绘制持久性多图的正确方法是什么?谢谢。 这是我的代码:

// functions and derivatives 
const board = JXG.JSXGraph.initBoard('jxgbox', {
  boundingbox: [-10, 10, 10, -10],
  axis: true
});

// Macro function plotter
function addCurve(board, func, atts) {
  var f = board.create('functiongraph', [func], atts);
  return f;
}

// Simplified plotting of function
function plot(func, atts) {
  if (atts == null) {
    return addCurve(board, func, {
      strokecolor: 'green',
      strokewidth: 2
    });
  } else {
    return addCurve(board, func, atts);
  }
}
    
// function of x
function f(x) {
  return Math.pow(x,2);
}

//draw f
c = plot(f);
  
//define derivative function, let command provide not to write "var" keyword
// in front of each variables

let ms=[],
  i=0,
  m=0,
  co=[],
  funcs=[],
  points=[];

for(i=0; i<11; i++) {
  m=(f(i+1)-f(i-1))/(i+1-i+1);
  co[i]=f(i)-m*i;    
  ms[i]=m;
  console.log("y="+ms[i]+"x+("+co[i]+")");
  
  // Create a function graph for each derivative function df(x) = ms[i]*x+co[i]
  funcs[i] = board.create('functiongraph',
    [function(x){ return ms[i]*x+co[i];}, -10, 10]
  );
  
  // Create a constrained point using anonymous function
    points[i] = board.create('point', [i, function () { return ms[i]; }]);  
}

console.log("aha"+c);

除了关于 letvar 的一些细节之外,您的示例代码是完全正确的。诀窍是在创建导数函数图的 for 循环块中用 let 定义 im,但要定义包含斜率的数组 (ms)和常数值 (co) 与 var。后者使数组持久化,前者相当于“手动”定义函数,如

funcs[0] = board.create('functiongraph', [
    function(x){ return ms[0] * x + co[0]; }, -10, 10]
);
funcs[1] = board.create('functiongraph', [
    function(x){ return ms[1] * x + co[1]; }, -10, 10]
);
...

这是循环的代码:

var c = plot(f);

var ms=[],
  co=[],
  funcs=[],
  points=[];

for (let i=0; i<11; i++) {
  let m = (f(i+1)-f(i-1)) / (i+1-i+1);
  co[i] = f(i) - m * i;    
  ms[i] = m;
  console.log("y=" + ms[i] + "x+(" + co[i] + ")");

  // Create a function graph for each derivative function df(x) = ms[i]*x+co[i]
  funcs[i] = board.create('functiongraph',
    [function(x){ return ms[i] * x + co[i]; }, -10, 10]
  );

  // Create a constrained point using anonymous function
  points[i] = board.create('point', [i, function () { return ms[i]; }]);  
}

https://jsfiddle.net/sp2ntf8v/

现场观看