Uncaught Error: Невозможно сделать обратный вызов из заданных данных, используя MathJax с p5 и html - PullRequest
0 голосов
/ 02 января 2019

Попытка динамически обновить верхнее уравнение с помощью mathjax, когда пользователи изменяют значения ползунков.Я понимаю, что mathjax запускается один раз, если его не отозвать.Я просмотрел их документы и попробовал: document.getElementById ("eqn"). InnerHTML = уравнение;(чтобы изменить текст) var math = MathJax.Hub.getAllJax ("eqn") [0];(захватить первый элемент с тегом eqn из html) MathJax.Hub.Queue (["Typeset", MathJax.Hub, math]);(очередь и повторный запуск mathjax для элемента), но я получаю сообщение об ошибке, описанное выше.

После исследования я не понял 1 или 2 исправления, и казалось, что большинство людей кодируют весь свой код в HTML, а непереходя туда-сюда с помощью javascript или p5.js.

Вот мой код ниже:

https://editor.p5js.org/philimr@nv.ccsd.net/sketches/SJtD0w4yE

let cols, rows;
let graphSize = 20;
let xCount = -10;
let yCount = -10;
let pointSpacing = 0.1;
let x = [];
let y = [];
let xdot = [];
let ydot = [];
let aSlider, bSlider, hSlider, kSlider, baseSlider;
let a, b, h, k, base;
let sliderChanged = null;
var AbsValcheckbox, Rationalcheckbox, Exponentialcheckbox, Quadcheckbox, Linearcheckbox, Logcheckbox, Cubiccheckbox, Sqrtcheckbox, Cubertcheckbox, ResetBox;
let tableOfValues = new p5.Table([21]);
let sliderHeight = 365; //30 spacing between each
let checkBoxHeight = 100;
let equation;
let newEqn;

function setup() {
  createCanvas(400, 400);
  AbsValcheckbox = createCheckbox('Absolute value');
  AbsValcheckbox.checked(true);
  AbsValcheckbox.changed(selectAbsVal);
  AbsValcheckbox.position(410, checkBoxHeight);
  Quadcheckbox = createCheckbox('Quadratic');
  Quadcheckbox.checked(null);
  Quadcheckbox.changed(selectAbsVal);
  Quadcheckbox.position(410, checkBoxHeight + 20);
  Cubiccheckbox = createCheckbox('Cubic');
  Cubiccheckbox.checked(null);
  Cubiccheckbox.changed(selectAbsVal);
  Cubiccheckbox.position(410, checkBoxHeight + 40);
  Linearcheckbox = createCheckbox('Linear');
  Linearcheckbox.checked(null);
  Linearcheckbox.changed(selectAbsVal);
  Linearcheckbox.position(410, checkBoxHeight + 60);
  Sqrtcheckbox = createCheckbox('Square Root');
  Sqrtcheckbox.checked(null);
  Sqrtcheckbox.changed(selectAbsVal);
  Sqrtcheckbox.position(410, checkBoxHeight + 80);
  Cubertcheckbox = createCheckbox('Cube Root');
  Cubertcheckbox.checked(null);
  Cubertcheckbox.changed(selectAbsVal);
  Cubertcheckbox.position(410, checkBoxHeight + 100);
  // Rationalcheckbox = createCheckbox('Rational');
  // Rationalcheckbox.checked(null);
  // Rationalcheckbox.changed(selectAbsVal);
  Logcheckbox = createCheckbox('Logarithmic');
  Logcheckbox.checked(null);
  Logcheckbox.changed(selectAbsVal);
  Logcheckbox.position(410, checkBoxHeight + 120);
  Exponentialcheckbox = createCheckbox('Exponential');
  Exponentialcheckbox.checked(null);
  Exponentialcheckbox.changed(selectAbsVal);
  Exponentialcheckbox.position(410, checkBoxHeight + 140);



  // let table = createElement('t1', 'here is my table');
  // table.position(200, 490);
  //table.html('new test');


  ResetBox = createButton('Reset');
  ResetBox.mousePressed(resetValues);
  ResetBox.position(450, sliderHeight - 50);

  let ahtml = createP('a').addClass('ahk');
  let hhtml = createP('h').addClass('ahk');
  let khtml = createP('k').addClass('ahk');
  let basehtml = createP('base').addClass('ahk');
  ahtml.position(415, sliderHeight - 15);
  hhtml.position(415, sliderHeight + 15);
  khtml.position(415, sliderHeight + 45);
  basehtml.position(400, sliderHeight + 75);



  aSlider = createSlider(-5, 5, 1, 0.01);
  aSlider.position(440, sliderHeight);
  a = aSlider.value();
  hSlider = createSlider(-9, 9, 0, 0.5);
  hSlider.position(440, sliderHeight + 30);
  h = hSlider.value();
  kSlider = createSlider(-9, 9, 0, 0.5);
  kSlider.position(440, sliderHeight + 60);
  k = kSlider.value();
  baseSlider = createSlider(0.1, 5, 2, 0.1);
  baseSlider.position(440, sliderHeight + 90);
  base = baseSlider.value();


  cols = floor(width / graphSize);
  rows = floor(height / graphSize);

  generateXArray();
  generateYArray();


  aInput = createInput();
  aInput.position(440 + aSlider.width + 10, sliderHeight);
  aInput.size(35, 21);
  aInput.value(a);
  hInput = createInput();
  hInput.position(440 + hSlider.width + 10, sliderHeight + 30);
  hInput.size(35, 21);
  hInput.value(h);
  kInput = createInput();
  kInput.position(440 + kSlider.width + 10, sliderHeight + 60);
  kInput.size(35, 21);
  kInput.value(k);
  baseInput = createInput();
  baseInput.position(440 + kSlider.width + 10, sliderHeight + 90);
  baseInput.size(35, 21);
  baseInput.value(base);

  newEqn = createP('eqn2', 'eqn2');


}

function draw() {
  background(255);

  if (AbsValcheckbox.checked()) {
    equation = '`f(x) = ' + a + ' * abs( x - ' + h + ') + ' + kInput.value() + '`';
  } else if (Quadcheckbox.checked()) {
    equation = 'f(x) = ' + a + ' * ( x - ' + h + ' )^2 + ' + kInput.value();
  } else if (Cubiccheckbox.checked()) {
    equation = 'f(x) = ' + a + ' * ( x - ' + h + ' )^3 + ' + kInput.value();
  } else if (Linearcheckbox.checked()) {
    equation = 'f(x) = ' + a + ' * ( x - ' + h + ' ) + ' + kInput.value();
  } else if (Logcheckbox.checked()) {
    equation = 'f(x) = ' + a + ' * log' + base + '( x - ' + h + ' ) + ' + kInput.value();
  } else if (Sqrtcheckbox.checked()) {
    equation = 'f(x) = ' + a + ' * sqrt( x - ' + h + ' ) + ' + kInput.value();
  } else if (Cubertcheckbox.checked()) {
    equation = 'f(x) = ' + a + ' * &#8731( x - ' + h + ' ) + ' + kInput.value();
  } else if (Exponentialcheckbox.checked()) {
    equation = 'f(x) = ' + a + ' * ' + base + '^( x - ' + h + ' ) + ' + kInput.value();
  }

  // newEqn.html(equation);


  // all of these give callback error
  document.getElementById("eqn").innerHTML = equation;
  var math = MathJax.Hub.getAllJax("eqn")[0];
  MathJax.Hub.Queue(["Typeset", MathJax.Hub, math]);

  stroke(150);
  strokeWeight(1);
  textAlign(CENTER, TOP);
  for (var i = 0; i <= width + 1; i++) {
    line(graphSize * i, 0, graphSize * i, height);
    //text(yCount, graphSize * i, -1 * height / 2, graphSize * i, height / 2);
  }
  for (var j = 0; j <= height + 1; j++) {
    line(0, graphSize * j, width, graphSize * j);
    //text(yCount, graphSize * i, -1 * height / 2, graphSize * i, height / 2);
  }
  for (var j = -1 * width / 2; j <= (width / 2); j++) {
    line(-1 * width / 2, graphSize * j, width / 2, graphSize * j);
  }
  // for (var m = 0; m <= width; m + graphSize){
  //   text(m, m, height/2);
  // }
  strokeWeight(2);
  stroke(50);
  line(0, height / 2, width, height / 2);
  line(width / 2, 0, width / 2, height);
  fill(0);
  noStroke();
  textAlign(LEFT, CENTER);
  textSize(20);
  push();
  translate(width / 2, height / 2);
  //rotate(2 * PI);
  noFill();
  stroke(0, 0, 255);
  beginShape();
  for (var k = 0; k <= x.length - 1; k++) {
    vertex(graphSize * x[k], graphSize * y[k]);
  }
  endShape();
  pop();
  checkSliderChanged();
  if (sliderChanged === true) {
    generateYArray();
  }
  aSlider.value(aInput.value());
  hSlider.value(hInput.value());
  kSlider.value(kInput.value());
  push();
  fill(0);
  noStroke();
  translate(width / 2, height / 2);
  for (m = 0; m < xdot.length; m++) {
    ellipse(xdot[m] * 20, ydot[m] * 20, 7, 7);
  }
  pop();
}

function checkSliderChanged() {
  if (a != aSlider.value() || h != hSlider.value() || k != kSlider.value() || base != baseSlider.value()) {
    generateYArray();
    aInput.value(a);
    hInput.value(h);
    kInput.value(k);
    baseInput.value(base);
    sliderChanged = false;
  } else {
    sliderChanged = false;
  }
}


// function createTable() {
//   var body = document.getElementsByTagName("body") [0];
//   var table = document.createElement('TABLE');
//   var tbody = document.createElement('TBODY');
//   var thead = document.createElement('TH');

//   table.appendChild(thead);
//   table.appendChild(tbody);
//   for (i = 0; i < 5; i++) {
//     var tr = document.createElement('TR');
//   	tbody.appendChild(tr);
//     //tr ='hi';


//     for (j = 0; j < 3; j++) {
//       var td = document.createElement('TD');
//       tr.appendChild(td);
//       //td = 'ok';
//     }
//   }
//   body.appendChild(table);
// }

function generateXArray() {
  for (var i = -width; i <= width; i += graphSize / 2) {
    x.push(i / (2 * cols));
  }
}



function generateYArray() {
  xdot = [];
  ydot = [];
  if (y.length > 0) {
    y.splice(0, y.length);
  }
  for (var i = 0; i < x.length; i++) {
    a = aSlider.value();
    h = hSlider.value();
    k = kSlider.value();
    base = baseSlider.value();

    if (AbsValcheckbox.checked()) {
      y.push((-1 * a * (abs(x[i] - h))) - k);
    }
    if (Quadcheckbox.checked()) {
      y.push(-1 * a * pow((x[i] - h), 2) - k);
    }
    if (Cubiccheckbox.checked()) {
      y.push(-1 * a * pow((x[i] - h), 3) + k);
    }
    if (Linearcheckbox.checked()) {
      y.push(-1 * a * (x[i] - h) - k);
    }
    if (Logcheckbox.checked()) {
      y.push(-1 * a * Math.log(x[i] - h) - k);
    }
    if (Sqrtcheckbox.checked()) {
      y.push(-1 * a * pow((x[i] - h), 0.5) - k);
    }
    if (Cubertcheckbox.checked()) {
      if (x[i] - h < 0) {
        y.push(1 * a * pow((-1 * x[i] + h), (1 / 3)) - k);
      } else {
        y.push(-1 * a * pow((x[i] - h), (1 / 3)) - k);
      }
    }
    //   if (Rationalcheckbox.checked()) {
    //     if(x[i]-h != 0){
    //     y.push( -1*(a / (x[i] - h), + k));
    //
    // }
    if (Exponentialcheckbox.checked()) {
      y.push(-1 * a * pow(base, (x[i] - h)) - k);
    }
    if (x[i] == int(x[i])) {
      if (y[i] == int(y[i])) {
        xdot.push(x[i]);
        ydot.push(y[i]);
        // console.table(xdot,ydot);
      }
    }
  }
  // createTable();
}



function selectAbsVal() {
  if (AbsValcheckbox.mouseClicked) {
    //AbsValcheckbox.checked(true);
    //Quadcheckbox.checked(false);
    generateYArray();
  }
  if (Quadcheckbox.mouseClicked) {
    //Quadcheckbox.checked(true);
    //AbsValcheckbox.checked(false);
    generateYArray();
  }
}

function resetValues() {
  a = 1;
  aInput.value(a);
  h = 0;
  hInput.value(h);
  k = 0;
  kInput.value(k);
  base = 2;
  baseInput.value(base);
  aSlider.value(aInput.value());
  hSlider.value(hInput.value());
  kSlider.value(kInput.value());
  baseSlider.value(baseInput.value());
  generateYArray();
}
html,
body {
  margin: 0;
  padding: 0;
}

#eqn {
  font-family: verdana;
  font-size: 150%;
}

.ahk {
  font-family: verdana;
  text-align: right;
  font-size: 108%;
}

canvas {
  display: block;
}
<!DOCTYPE html>
<html>

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/p5.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/addons/p5.dom.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/addons/p5.sound.min.js"></script>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML' async></script>
  <link rel="stylesheet" type="text/css" href="style.css">
  <meta charset="utf-8" />

</head>

<body>
  <script src="sketch.js"></script>

  <p id="eqn"> `f(x) = a * abs(x - h) + k`
  </p>

</body>

</html>

1 Ответ

0 голосов
/ 02 января 2019

Проблема в этом коде:

document.getElementById("eqn").innerHTML = equation;
var math = MathJax.Hub.getAllJax("eqn")[0];
MathJax.Hub.Queue(["Typeset", MathJax.Hub, math]);

, и проблема в том, что когда вы установили innerHTML, вы еще не запустили MathJax на нем, и поэтому Jax не будетнайдено (MathJax вставляет их, когда набирает математику).Таким образом, значение math равно нулю, и это вызывает проблему с вызовом Typeset, который вы ставите в очередь, так как MathJax пытается преобразовать ваш null в обратный вызов, который будет вызван после завершения набора текста.Это приводит к ошибке.

Вместо этого попробуйте

document.getElementById("eqn").innerHTML = equation;
MathJax.Hub.Queue(["Typeset", MathJax.Hub, "eqn"]);

вместо исходных трех строк, чтобы получить новое содержимое элемента eqn для набора текста.В качестве альтернативы вы можете использовать

var math = MathJax.Hub.getAllJax("eqn")[0];
MathJax.Hub.Queue(["Text", math, equation]);

для замены исходных строк, чтобы указать существующему уравнению изменить его выражение на новое (не нужно использовать innerHTML).

...