plot.html (1566B)
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="utf-8"> 5 <title>math.js | plot</title> 6 <script src="../../lib/browser/math.js"></script> 7 8 <script src="https://cdn.plot.ly/plotly-1.35.2.min.js"></script> 9 10 <style> 11 input[type=text] { 12 width: 300px; 13 } 14 input { 15 padding: 6px; 16 } 17 body, html, input { 18 font-family: sans-serif; 19 font-size: 11pt; 20 21 } 22 form { 23 margin: 20px 0; 24 } 25 </style> 26 </head> 27 <body> 28 29 <form id="form"> 30 <label for="eq">Enter an equation:</label> 31 <input type="text" id="eq" value="4 * sin(x) + 5 * cos(x/2)" /> 32 <input type="submit" value="Draw" /> 33 </form> 34 35 <div id="plot"></div> 36 37 <p> 38 Used plot library: <a href="https://plot.ly/javascript/">Plotly</a> 39 </p> 40 41 <script> 42 function draw() { 43 try { 44 // compile the expression once 45 const expression = document.getElementById('eq').value 46 const expr = math.compile(expression) 47 48 // evaluate the expression repeatedly for different values of x 49 const xValues = math.range(-10, 10, 0.5).toArray() 50 const yValues = xValues.map(function (x) { 51 return expr.evaluate({x: x}) 52 }) 53 54 // render the plot using plotly 55 const trace1 = { 56 x: xValues, 57 y: yValues, 58 type: 'scatter' 59 } 60 const data = [trace1] 61 Plotly.newPlot('plot', data) 62 } 63 catch (err) { 64 console.error(err) 65 alert(err) 66 } 67 } 68 69 document.getElementById('form').onsubmit = function (event) { 70 event.preventDefault() 71 draw() 72 } 73 74 draw() 75 </script> 76 77 </body> 78 </html>