Make text area size configurable in pixels.
[dygraphs.git] / gallery / plotter.js
1 // Use this as a template for new Gallery entries.
2 Gallery.register(
3 'plotter',
4 {
5 name: 'Function Plotter',
6 title: 'Define your data with functions',
7 setup: function(parent) {
8 parent.innerHTML = [
9 "<p><b>Equation: </b><br/>",
10 "<textarea cols='80' rows='10' id='eq'>function(x) {",
11 " return [0.1 * x, 0.1 * x + Math.sin(x), 0.1*x + Math.cos(x)];",
12 "}</textarea><br/>",
13 "<b>Preset functions:</b> <select id='presets'>",
14 "<option id='custom'>(custom)</option>",
15 "<option id='id'>Identity</option>",
16 "<option id='sine'>Sine Wave</option>",
17 "<option id='taylor'>Taylor series</option>",
18 "<option selected id='sawtooth'>Sawtooth</option>",
19 "</select>",
20 "</p>",
21 "",
22 "<p><b>x range: </b> <input type='text' width='5' id='x1' value='-10' />",
23 "to <input type='text' width='5' id='x2' value='10' /></p>",
24 "<p><button id='plot'>Plot</button></p>",
25 "",
26 "<div id='graph_div' style='width:600px; height:300px;'></div>"].join("\n");
27
28 },
29 run: function() {
30 var select = document.getElementById("presets");
31 select.onchange = function() {
32 var sel = select.selectedIndex;
33 var id = select.options[sel].id;
34 var presets = {
35 'id': [ -10, 10, 'function(x) {\n return x;\n}' ],
36 'sine': [ -10, 10, 'function(x) {\n return Math.sin(x);\n}' ],
37 'taylor': [ -3, 3, 'function(x) {\n return [Math.cos(x), 1 - x*x/2 + x*x*x*x/24];\n}' ],
38 'sawtooth': [-10, 10, 'function(x) {\n var y = 0;\n for (var i = 1; i < 20; i+=2) {\n y += Math.sin(i * x)/i;\n }\n var final = 1 - 2*(Math.abs(Math.floor(x / Math.PI)) % 2);\n return [4/Math.PI * y, final];\n}' ]
39 };
40
41 if (id == "custom") { return; }
42 document.getElementById("x1").value = presets[id][0];
43 document.getElementById("x2").value = presets[id][1];
44 document.getElementById("eq").value = presets[id][2];
45 plot();
46 }
47
48 var plotButton = document.getElementById("plot");
49 var plot = function() {
50 var eq = document.getElementById("eq").value;
51 eval("fn = " + eq);
52
53 var graph = document.getElementById("graph_div");
54 var width = parseInt(graph.style.width);
55 var x1 = parseFloat(document.getElementById("x1").value);
56 var x2 = parseFloat(document.getElementById("x2").value);
57 var xs = 1.0 * (x2 - x1) / width;
58
59 var data = [];
60 for (var i = 0; i < width; i++) {
61 var x = x1 + i * xs;
62 var y = fn(x);
63 var row = [x];
64 if (y.length > 0) {
65 for (var j = 0; j < y.length; j++) {
66 row.push(y[j]);
67 }
68 } else {
69 row.push(y);
70 }
71 data.push(row);
72 }
73
74 g = new Dygraph(graph, data);
75 }
76 plot.onclick = plot;
77 plot();
78 }
79 });