-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
496 lines (408 loc) · 14.3 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
<html><head>
<title>Truthy Graph</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.0/jquery-ui.min.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/3.3.0/math.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.0/jquery-ui.min.js"></script>
<style>
html, body {
width: 100%;
height: 100%;
margin: 0;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
color: #333;
}
a, a:visited, a:link, a:hover, a:active {
color: #FFFF64;
}
#main {
position:relative;
height: 100%;
width:100%;
}
#controls {
width: 250px;
z-index: 10;
position: absolute;
left: 0;
top: 0;
background-color: #fff;
background-color: rgba(255,255,255,0.5);
padding: 10px;
color: white;
font-weight: lighter;
letter-spacing: 1px;
cursor: move;
}
.title {
font-family: "Raleway", "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 150%;
letter-spacing: 4px;
font-weight: 100;
color: white;
margin: 5px 0;
text-align: center;
}
#footer-info {
font-size: 0.7em;
}
#equation {
border: 1px solid #ccc;
border-radius: 4px;
padding: 8px;
font-size: 16px;
width: 100%;
margin-bottom: 5px;
}
#canvas {
border: 1px solid #ccc;
cursor: move;
float: left;
width: 100%;
height:100%;
position:absolute;
}
.zoom-btn {
padding: 5px 10px;
}
fieldset {
-moz-border-radius:5px;
border-radius: 5px;
-webkit-border-radius: 5px;
}
</style>
</head><body>
<div id="main">
<div id="controls">
<h1 class="title">Truthy Graph</h1>
<div>
<input type="equation" id="equation" placeholder="y^2 = x^3 - x + 1">
<fieldset>
<legend>Fuzzy level</legend>
<div id="fuzzy-slider"></div>
</fieldset>
<fieldset>
<legend>Zoom</legend>
<button id="zoom-in-btn" class="zoom-btn">+</button>
<button id="zoom-out-btn" class="zoom-btn">-</button>
</fieldset>
<hr />
<div id="footer-info">
<span>Project by <a href="http://calebmadrigal.com">Caleb Madrigal</a> - <a href="https://github.com/calebmadrigal/truthygraph">View on Github</a></span>
</div>
</div>
</div>
<canvas id="canvas">
Your browser does not support HTML5 Canvas.
</canvas>
</div>
<script type="text/javascript">
ZOOM_RATE = 1.2;
MAX_FUZZY = 200;
//////////////////////////////////////////////////////////////////////////////////// Math functions
// Returns a function maps from the inRange to the outRange
var makeLinearMapper = function(inRange, outRange, intOut) {
var inDelta = inRange[1] - inRange[0];
var outDelta = outRange[1] - outRange[0];
// y = mx + b (m = slope, b = y-intersect)
var m = (outDelta / inDelta);
// To find b: b = y - mx
// Just plug in first item of each range
var b = outRange[0] - m * inRange[0];
if (intOut) {
var linearMapper = function(val) {
return Math.round(m * val + b);
}
}
else {
var linearMapper = function(val) {
return m * val + b;
}
}
return linearMapper;
};
var parseEquationString = function(eq_str) {
var split_result = eq_str.split("=");
if (split_result.length != 2) {
return null;
}
var left_eq = math.eval('f(x, y) = ' + split_result[0], {});
var right_eq = math.eval('f(x, y) = ' + split_result[1], {});
var error_func = function (x, y) { return Math.abs(left_eq(x, y) - right_eq(x, y)); };
return error_func;
};
var getXMin = function (xWidth, xCenter) {
return -1 * xWidth / 2 + xCenter;
};
var getXMax = function (xWidth, xCenter) {
return xWidth / 2 + xCenter;
};
var getYMin = function (yWidth, yCenter) {
return -1 * yWidth / 2 + yCenter;
};
var getYMax = function (yWidth, yCenter) {
return yWidth / 2 + yCenter;
};
var getHeightToWidthMultiplier = function(xWidth, yWidth) {
return xWidth / yWidth;
};
var getXWidth = function(yWidth, canvasWidth, canvasHeight) {
return yWidth * getHeightToWidthMultiplier(canvasWidth, canvasHeight);
};
var calcWindowBounds = function(xCenter, yCenter, yWidth, canvasWidth, canvasHeight) {
// Calculate xWidth based on yWidth
var xWidth = getXWidth(yWidth, canvasWidth, canvasHeight);
// Calculate x and y min and max based on window size and center
return {
'xMin': getXMin(xWidth, xCenter),
'xMax': getXMax(xWidth, xCenter),
'yMin': getYMin(yWidth, yCenter),
'yMax': getYMax(yWidth, yCenter)
};
};
var calculateFuncForWindow = function(func, window, canvasWidth, canvasHeight) {
var pixel_to_x_mapper = makeLinearMapper([0, canvasWidth], [window['xMin'], window['xMax']], false);
var pixel_to_y_mapper = makeLinearMapper([canvasHeight, 0], [window['yMin'], window['yMax']], false);
var minValue = 9999999;
var maxValue = -9999999;
var maxCutoff = 100;
var pixelValues = new Array(canvasWidth * canvasHeight);
// Calculate values for each pixel, and find the min and max values
for (var pixelX = 0; pixelX < canvasWidth; pixelX++) {
for (var pixelY = 0; pixelY < canvasHeight; pixelY++) {
var x = pixel_to_x_mapper(pixelX);
var y = pixel_to_y_mapper(pixelY);
var result = func(x, y);
result = Math.min(result, maxCutoff);
if (result > maxValue) {
maxValue = result;
}
if (result < minValue) {
minValue = result;
}
pixelValues[(pixelY * canvasWidth) + pixelX] = result;
}
}
return {'pixelValues': pixelValues, 'max': maxValue, 'min': minValue};
};
////////////////////////////////////////////////////////////////////////////////////// Display stuff
var makeColorMapper = function(minInput, maxInput) {
var colorChannelRange = [0, 255];
var colorMapper = makeLinearMapper([minInput, maxInput], colorChannelRange, true);
var mapper = function(val) {
var colorVal = colorMapper(val);
return [colorVal, colorVal, 100];
};
return mapper;
};
var displayTruthyGraph = function(pixelValues, minValue, maxValue, fuzzyValue, canvasElem) {
var context = canvasElem.getContext('2d');
var canvasWidth = context.canvas.width;
var canvasHeight = context.canvas.height;
var imageData = context.createImageData(canvasWidth, canvasHeight);
var pixelData = imageData.data;
// Function to modify the value to make the graph look more interesting
// We do this because the value is a measure of error, but we want more error
// to look like a more intense value on the graph
var valueModifier = function (value) {
return Math.pow(maxValue - value, MAX_FUZZY - fuzzyValue);
};
// Determine the color scale based on the min and max values
var colorMapper = makeColorMapper(valueModifier(maxValue), valueModifier(minValue));
// Set the color for each pixel based on the values
for (var x = 0; x < canvasWidth; x++) {
for (var y = 0; y < canvasHeight; y++) {
var value = pixelValues[y * canvasWidth + x];
var color = colorMapper(valueModifier(value));
// Set pixel color channels
var pixelOffset = (canvasWidth * y + x) * 4;
pixelData[pixelOffset] = color[0]; // red
pixelData[pixelOffset + 1] = color[1]; // green
pixelData[pixelOffset + 2] = color[2]; // blue
pixelData[pixelOffset + 3] = 255; // alpha
}
}
context.putImageData(imageData, 0, 0);
};
var displayGraph = function(graphParams, canvasElem) {
var window = calcWindowBounds(graphParams['xCenter'],
graphParams['yCenter'],
graphParams['yWidth'],
graphParams['canvasWidth'],
graphParams['canvasHeight']);
var pixelValues = calculateFuncForWindow(graphParams['equationCompiled'],
window,
graphParams['canvasWidth'],
graphParams['canvasHeight']);
displayTruthyGraph(pixelValues['pixelValues'],
pixelValues['min'],
pixelValues['max'],
graphParams['fuzzyValue'],
canvasElem);
};
var zoomIn = function(graphParams, canvasElem) {
graphParams['yWidth'] = graphParams['yWidth'] * (1/ZOOM_RATE);
displayGraph(graphParams, canvasElem);
};
var zoomOut = function(graphParams, canvasElem) {
graphParams['yWidth'] = graphParams['yWidth'] * ZOOM_RATE;
displayGraph(graphParamsGlobal, canvasElem);
};
var panGraph = function(graphParams, xOffsetPixels, yOffsetPixels, canvasElem) {
var xWidth = getXWidth(graphParams['yWidth'], graphParams['canvasWidth'], graphParams['canvasHeight']);
// First, we have to convert the offset in pixels into the offset in our graphing window
var xOffset = xOffsetPixels * (xWidth / graphParams['canvasWidth']);
var yOffset = yOffsetPixels * (graphParams['yWidth'] / graphParams['canvasHeight']);
// Then we need to move the center of our graphing window accordingly
graphParams['xCenter'] = graphParams['xCenter'] - xOffset;
graphParams['yCenter'] = graphParams['yCenter'] + yOffset; // Due to flipped y, negate yOffset (and -1*-1 = 1)
displayGraph(graphParams, canvasElem);
};
/////////////////////////////////////////////////////////////////////////////////////// URL Handling
var getParameterByName = function(name, url) {
// Copied from:
// http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
};
var setParamsFromUrl = function (graphParams) {
// Try to get equation from url
var urlFragmentId = window.location.hash.substr(1);
var getParamFromUrl = function (param) {
var paramValFromUrl = getParameterByName(param, urlFragmentId);
if (paramValFromUrl) {
// if 'equation' param, compile it
if (param == 'equation') {
graphParams[param] = paramValFromUrl;
var equationCompiled = parseEquationString(paramValFromUrl);
if (equationCompiled) {
graphParams['equationCompiled'] = equationCompiled;
}
}
// Otherwise, it's a numeric value, so parse it as a float
else {
graphParams[param] = parseFloat(paramValFromUrl);
}
console.log("Got url param:" + param + " -> " + paramValFromUrl);
}
};
for (var param in graphParams) {
if (graphParams.hasOwnProperty(param)) {
getParamFromUrl(param);
}
}
};
var setUrlFromParams = function(graphParams) {
var hashStr = "#?equation=" + encodeURIComponent(graphParams['equation']);
['fuzzyValue', 'xCenter', 'yCenter', 'yWidth'].forEach(function (param) {
hashStr = hashStr + "&" + param + "=" + encodeURIComponent(graphParams[param]);
});
window.location.hash = hashStr;
};
////////////////////////////////////////////////////////////////////////////////////// Initial stuff
// jQuery UI crap
$("#controls").draggable({ snap: "#main" });
$("button").button();
$('input').addClass("ui-corner-all");
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
// Setup default parameters
var graphParamsGlobal = {
'equation': 'y^2 = x^3 - x + 1',
'equationCompiled': parseEquationString('y^2 = x^3 - x + 1'),
'fuzzyValue': 70,
'xCenter': 0,
'yCenter': 0,
'yWidth': 6,
'canvasWidth': context.canvas.width,
'canvasHeight': context.canvas.height
};
// Try to get graph params from url
setParamsFromUrl(graphParamsGlobal);
console.log('graphParamsGlobal: ', graphParamsGlobal);
///////////////////////////////////////////////////////////////////////////////////// Event handlers
//////////// Equation change handler
var equationInput = document.getElementById('equation');
equationInput.value = graphParamsGlobal['equation'];
var equationChangeHandler = function() {
try {
var equationToGraph = parseEquationString(equationInput.value);
if (equationToGraph) {
graphParamsGlobal['equation'] = equationInput.value;
graphParamsGlobal['equationCompiled'] = equationToGraph;
displayGraph(graphParamsGlobal, document.getElementById('canvas'));
setUrlFromParams(graphParamsGlobal);
}
}
catch(err) {
return 0;
}
};
equationInput.addEventListener('input', equationChangeHandler);
//////////// Fuzzy value handlers
var updateFuzzy = function(nr, val) {
graphParamsGlobal['fuzzyValue'] = parseInt(val.value);
displayGraph(graphParamsGlobal, document.getElementById('canvas'));
setUrlFromParams(graphParamsGlobal);
};
$('#fuzzy-slider').slider({
range: "min",
min: 1,
max: MAX_FUZZY,
value: graphParamsGlobal['fuzzyValue'],
slide: updateFuzzy,
change: updateFuzzy
});
//////////// Zoom handlers
document.getElementById('zoom-in-btn').onclick = function () {
zoomIn(graphParamsGlobal, document.getElementById('canvas'));
setUrlFromParams(graphParamsGlobal);
};
document.getElementById('zoom-out-btn').onclick = function () {
zoomOut(graphParamsGlobal, document.getElementById('canvas'));
setUrlFromParams(graphParamsGlobal);
};
//////////// Pan handlers
var mouseIsDown = false;
var dragStart = {};
var dragStop = {};
canvas.onmousedown = function(e){
dragStart.x = e.x;
dragStart.y = e.y;
mouseIsDown = true;
};
canvas.onmouseup = function(e){
mouseIsDown = false;
dragStop.x = e.x;
dragStop.y = e.y;
panGraph(graphParamsGlobal, dragStop.x - dragStart.x, dragStop.y - dragStart.y, document.getElementById('canvas'));
setUrlFromParams(graphParamsGlobal);
};
canvas.onmousemove = function(e){
if(!mouseIsDown) return;
dragStop.x = e.x;
dragStop.y = e.y;
return false;
};
//////////// Window resize handling
var makeCanvasFullPage = function () {
context.canvas.width = window.innerWidth;
context.canvas.height = window.innerHeight;
graphParamsGlobal['canvasWidth'] = context.canvas.width;
graphParamsGlobal['canvasHeight'] = context.canvas.height;
};
window.onresize = function(event) {
makeCanvasFullPage();
displayGraph(graphParamsGlobal, document.getElementById('canvas'));
};
/////////////////////////////////////////////////////////////////////////////////////////////// Main
// Do initial render
makeCanvasFullPage();
displayGraph(graphParamsGlobal, document.getElementById('canvas'));
</script>
</body></html>