-
Notifications
You must be signed in to change notification settings - Fork 1
/
renderMath.js
3000 lines (2844 loc) · 151 KB
/
renderMath.js
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var loadingLogoHTML = `
<style>
.loader {
border: 3px solid #f3f3f3; /* Light grey */
border-top: 3px solid #3498db; /* Blue */
border-radius: 50%;
width: 25px;
height: 25px;
animation: spin 1.4s linear infinite;
}
.mobile .studyGuideDropdown .loader {
border: 6px solid #f3f3f3;
/* Light grey */
border-top: 6px solid #3498db;
/* Blue */
border-radius: 50%;
width: 50px;
height: 50px;
animation: spin 1.4s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>
<div class="loader"></div>
`;
function addImportanceToFormulas() {
var elementQueryList = [".rules td"]; //Use CSS Selectors Here
elementQueryList.forEach((elementQuery) => {
var elementList = document.querySelectorAll(elementQuery);
elementList.forEach((element) => {
element.classList.add("important"); //This line adds a class that has predefined styles in the CSS file
});
});
}
function removeImportanceFromElements() {
var elementQueryList = ["sigma td", "matrix td", ".chemicalElement td"]; //Use CSS Selectors Here
elementQueryList.forEach((elementQuery) => {
var elementList = document.querySelectorAll(elementQuery);
elementList.forEach((element) => {
element.classList.remove("important"); //This line adds a class that has predefined styles in the CSS file
});
});
}
function renderMath(parentElement = "") {
//Convert my format of showing Math to MathJax - leave commented out for now until further use...only use on chem study guide for now
function createHTMLNodesFromString(htmlString) {
var div = document.createElement("div");
div.innerHTML = htmlString;
return div.childNodes;
}
var equationTags = document.querySelectorAll(parentElement + " equation");
if (equationTags.length > 0) {
/* Session Storage failed on refresh
//If sessionStorage doesn't have pages saved where mathjax was loaded or if this page hasn't already loaded mathjax
if (!sessionStorage.getItem("pagesThatLoadedMathJax") || !JSON.parse(sessionStorage.getItem("pagesThatLoadedMathJax")).includes(window.location.href))
*/
if (document.querySelector("#MathJax-Script") == null) {
//Set MathJax Config
window.MathJax = {
chtml: {
scale: 1
},
options: {
enableMenu: false
},
tex: {
packages: {
'[+]': ['mhchem']
}
},
loader: {
load: ['[tex]/mhchem']
}
};
/*
Import MathJax
<!--Use this to edit MathJax: https://en.wikipedia.org/wiki/Quadratic_equation?veaction=edit-->
<!-- Import MathJax -->
<script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
*/
var polyfillScript = document.createElement("script");
polyfillScript.setAttribute("src", "https://polyfill.io/v3/polyfill.min.js?features=es6");
var mathjaxScript = document.createElement("script");
mathjaxScript.setAttribute("id", "MathJax-script");
mathjaxScript.setAttribute("async", "");
mathjaxScript.setAttribute("src", "https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js");
document.head.appendChild(polyfillScript);
document.head.appendChild(mathjaxScript);
/*
//Take care of saving the information that this page has saved mathjax once and does not need to repeat
if (!sessionStorage.getItem("pagesThatLoadedMathJax")) {
var array = [];
array.push(window.location.href);
sessionStorage.setItem("pagesThatLoadedMathJax", JSON.stringify(array));
} else {
var array = JSON.parse(sessionStorage.getItem("pagesThatLoadedMathJax"));
array.push(window.location.href);
sessionStorage.setItem("pagesThatLoadedMathJax", JSON.stringify(array));
}
*/
}
//Convert my math to TeX for MathJax
equationTags.forEach((equationTag) => {
var innerMath = "\\(";
//Convert the innerHTML into DOM
var dom = equationTag.cloneNode(true); //Set true for a deep copy
//var myString = equationTag.innerHTML;
//Replace sup{} with ^{}
dom.innerHTML = dom.innerHTML.replace(/−/gi, "-")
//Replace the grouping punctuation with those that resize
.replaceAll("||", "∥") //Allows to show magnitude of vectors
.replaceAll("(", "\\left(").replaceAll(")", "\\right)")
.replaceAll("[", "\\left[").replaceAll("]", "\\right]")
.replaceAll(createHTMLNodesFromString("⟨")[0].textContent, "\\left\\langle ").replaceAll(createHTMLNodesFromString("⟩")[0].textContent, "\\right\\rangle ")
//The following line comes from: https://stackoverflow.com/questions/406230/regular-expression-to-match-a-line-that-doesnt-contain-a-word
.replace(/^((?!\\ce).){0,9}({[^}]{1,}})$/gmi, "\\left\\{$2\\right\\}")
//.replaceAll("{", "\\left\\{").replaceAll("}", "\\right\\}")
.replace(/[|]([^|]{1,})[|]/gm, "\\left\\vert {$1} \\right\\vert ");
//.replaceAll("⟨", "hello")
//.replace(/[⟨⟨]/gi, "hello").replace(/⟩/gi, "\\right⟩")
//Replace HTML entities so they don't show up small on mobile
var symbols = ["theta", "alpha", "beta", "gamma", "pi", "rho", "phi", "omega", "tau", "epsilon", "kappa", "mu"];
for (var symbol of symbols) {
var regularExpression = new RegExp(createHTMLNodesFromString(`&${symbol};`)[0].textContent, "gmi"); //Create regular expression for each html entity in symbolic form
dom.innerHTML = dom.innerHTML.replace(regularExpression, `\\${symbol} `); //Actually replace with MathJax counterpart
}
/*
.replace(/θ/gi, "\\theta").replace(/α/gi, "\\alpha")
.replace(/β/gi, "\\beta").replace(/γ/gi, "\\gamma")
.replace(/π/gi, "\\pi").replace(/ρ/gi, "\\rho").replace(/φ/gi, "\\phi")
.replace(/ω/gi, "\\omega").replace(/τ/gi, "\\tau")
.replace(/ε/gi, "\\epsilon").replace(/κ/gi, "\\kappa")
.replace(/μ/gi, "\\mu")
//.replace(/−/g, "-").replace(/Δ/g, "\\Delta")
//.replaceAll("⟨", "\\big\\langle").replaceAll("⟩", "\\right\\langle")
//.replaceAll(",", ",\\,") //adds a space after every comma
/*
.replace(/[\[]([^\]]{1,})[\]]/gm, "\\left[ {$1} \\right]").replace(/[\(]([^\)]{1,})[\)]/gm, "\\left( {$1} \\right)")
.replace(/[\{]([^})]{1,})[\}]/gm, "\\left\\{ {$1} \\right\\}")*/
while (dom.querySelector("sigma") != undefined) {
var oldSigma = dom.querySelector("sigma");
var startValue = (oldSigma.getAttribute("start") !== null) ? oldSigma.getAttribute("start") : "";
var endValue = (oldSigma.getAttribute("end") !== null) ? oldSigma.getAttribute("end") : "";
var newSigma = createHTMLNodesFromString("\\displaystyle\\sum_{" + startValue + "}^{" + endValue + "}");
oldSigma.replaceWith(...newSigma);
}
while (dom.querySelector("integral") != undefined) {
var oldIntegral = dom.querySelector("integral");
var numberOfIntegrals = 1;
if (oldIntegral.hasAttribute("double")) {
//Then it is a double integral
numberOfIntegrals = 2;
}
if (oldIntegral.hasAttribute("triple")) {
numberOfIntegrals = 3;
}
var lowerBound = (oldIntegral.getAttribute("lowerBound") != null) ? oldIntegral.getAttribute("lowerBound") : "";
var upperBound = (oldIntegral.getAttribute("upperBound") != null) ? oldIntegral.getAttribute("upperBound") : "";
var respectTo = (oldIntegral.getAttribute("respectTo") != null) ? "d" + oldIntegral.getAttribute("respectTo") : "";
var newIntegral = createHTMLNodesFromString("\\displaystyle\\" + "i".repeat(numberOfIntegrals) + "nt_{" + lowerBound + "}^{" + upperBound + "} {" + oldIntegral.innerHTML + "}" + respectTo);
oldIntegral.replaceWith(...newIntegral);
}
//Replace sqrt{} with \sqrt {}
while (dom.querySelector("sqrt") != undefined) {
var oldSQRT = dom.querySelector("sqrt");
var newSQRT = createHTMLNodesFromString("\\sqrt {" + oldSQRT.innerHTML + "}");
oldSQRT.replaceWith(...newSQRT);
//console.log(dom.innerHTML)
}
// <nthRoot n="3"></nthRoot> (for 3rd root and so on)
while (dom.querySelector("nthRoot") != undefined) {
var oldNthRoot = dom.querySelector("nthRoot");
var n = oldNthRoot.getAttribute("n");
var newNthRoot = createHTMLNodesFromString(`\\sqrt[${n}]{${oldNthRoot.innerHTML}}`);
oldNthRoot.replaceWith(...newNthRoot);
}
while (dom.querySelector("evaluated") != undefined) {
var oldEvaluated = dom.querySelector("evaluated");
var from = (oldEvaluated.getAttribute("from") != null) ? oldEvaluated.getAttribute("from") : "";
var to = (oldEvaluated.getAttribute("to") != null) ? oldEvaluated.getAttribute("to") : "";
var newEvaluated = createHTMLNodesFromString("\\Biggr|_{" + from + "}^{" + to + "}"); //Needs to be fixed!!!!
oldEvaluated.replaceWith(...newEvaluated);
}
while (dom.querySelector("div.fraction") != undefined) {
var oldFrac = dom.querySelector("div.fraction");
var top = oldFrac.children[0].innerHTML;
var bottom = oldFrac.children[1].innerHTML;
var newFrac = createHTMLNodesFromString("\\dfrac{" + top + "}{" + bottom + "}");
oldFrac.replaceWith(...newFrac);
//console.log(dom.innerHTML)
}
while (dom.querySelector("log") != undefined) {
var oldLog = dom.querySelector("log");
var base = oldLog.getAttribute("base");
var newLog = "";
if (base !== null) {
newLog = "\\log_{" + base + "} {" + oldLog.innerHTML + "}";
} else {
newLog = "\\log {" + oldLog.innerHTML + "}";
}
newLog = createHTMLNodesFromString(newLog);
oldLog.replaceWith(...newLog);
//console.log(dom.innerHTML)
}
while (dom.querySelector("lim") != undefined) {
var oldLim = dom.querySelector("lim");
var limAs = oldLim.getAttribute("as");
var limApproaches = oldLim.getAttribute("approaches");
var newLim = createHTMLNodesFromString("\\displaystyle\\lim_{" + limAs + " \\to " + limApproaches + "}");
oldLim.replaceWith(...newLim);
}
while (dom.querySelector("derivative") != undefined) {
var oldDerivative = dom.querySelector("derivative");
var derivativeOf = oldDerivative.getAttribute("of") ? oldDerivative.getAttribute("of") : "";
var derivativeRespectTo = oldDerivative.getAttribute("respectTo") ? oldDerivative.getAttribute("respectTo") : "x";
var derivativeOrder = oldDerivative.getAttribute("order") ? "^{" + oldDerivative.getAttribute("order") + "}" : "";
var newDerivative = createHTMLNodesFromString("\\dfrac{d" + derivativeOrder + derivativeOf + "}{d" + derivativeRespectTo + derivativeOrder + "}");
oldDerivative.replaceWith(...newDerivative);
}
while (dom.querySelector("pDerivative") != undefined) {
var oldPDerivative = dom.querySelector("pDerivative");
var pDerivativeOf = oldPDerivative.getAttribute("of") ? oldPDerivative.getAttribute("of") : "";
var pDerivativeRespectTo = oldPDerivative.getAttribute("respectTo") ? oldPDerivative.getAttribute("respectTo") : "x";
var pDerivativeOrder = oldPDerivative.getAttribute("order") ? "^{" + oldPDerivative.getAttribute("order") + "}" : "";
var newPDerivative = createHTMLNodesFromString("\\dfrac{\\partial " + pDerivativeOrder + pDerivativeOf + "}{\\partial " + pDerivativeRespectTo + pDerivativeOrder + "}");
oldPDerivative.replaceWith(...newPDerivative);
}
while (dom.querySelector("laPlaceTransform") != undefined) {
var oldLaPlaceTransform = dom.querySelector("laPlaceTransform");
var newLaPlaceTransform = createHTMLNodesFromString("ℒ\\left\\{" + oldLaPlaceTransform.innerHTML + "\\right\\}");
oldLaPlaceTransform.replaceWith(...newLaPlaceTransform);
}
while (dom.querySelector("invLaPlaceTransform") != undefined) {
var oldInvLaPlaceTransform = dom.querySelector("invLaPlaceTransform");
var newInvLaPlaceTransform = createHTMLNodesFromString("ℒ^{-1}\\left\\{" + oldInvLaPlaceTransform.innerHTML + "\\right\\}");
oldInvLaPlaceTransform.replaceWith(...newInvLaPlaceTransform);
}
while (dom.querySelector("matrix") != undefined) {
var oldMatrix = dom.querySelector("matrix");
var dimensionX = parseInt(oldMatrix.getAttribute("dimensionX"));
var dimensionY = parseInt(oldMatrix.getAttribute("dimensionY"));
/*
Since this attribute is stored in string format, everything that comes before it is not actually rendered
since it is not a DOM element, so for matrices of pDerivatives and what not, also support innerHTML
Still support getAttribute("values") for backwards compatability, since there are a lot of matrices already on these study guides
*/
var values = [];
if (oldMatrix.hasAttribute("values")) {
values = oldMatrix.getAttribute("values").split(", "); //Insert values in comma separated list format
} else {
// Rely on innerHTML, still comma-separated values - maybe change that to something else?
// NVMD we can't rely on comma separated values, commas are too common in math - prone to throw avoidable errors
// Use a new <cell> element for each cell of the matrix
while (oldMatrix.querySelector("cell") != undefined) {
var oldCell = oldMatrix.querySelector("cell");
values.push(oldCell.innerHTML); //still keep the same `values` functionality, just change the `values` collection method
//Now we need to remove this cell from the matrix so that we don't accidentally loop back to it again
oldCell.replaceWith(...createHTMLNodesFromString("")); // Replace with empty string node since I am lazy to find the right way to actually take care of this
}
//values = oldMatrix.innerHTML.split(",");
}
if (values.length !== dimensionX * dimensionY) {
console.log(values);
oldMatrix.innerHTML = "Could not display matrix, Dimension Error";
} else {
var punctuation = "bmatrix";
//If it is a direct sibling of determinant <det> then make it absolute value signs instead
if (oldMatrix.parentElement.localName === "det") {
punctuation = "vmatrix";
}
var newMatrixString = "\\begin{" + punctuation + "}";
for (var row = 1; row <= dimensionY; row++) {
for (var col = 1; col <= dimensionX; col++) {
newMatrixString += values[(row - 1) * dimensionX + (col - 1)];
if (col != dimensionX) {
newMatrixString += " & ";
}
}
if (row != dimensionY) {
newMatrixString += "\\\\";
}
}
newMatrixString += "\\end{" + punctuation + "}";
var newMatrix = createHTMLNodesFromString(newMatrixString);
oldMatrix.replaceWith(...newMatrix);
}
}
while (dom.querySelector("det") != undefined) {
var oldDet = dom.querySelector("det");
var writeDet = false;
if (oldDet.hasAttribute("writeDet")) {
writeDet = true;
}
var newDet;
//If the child of the determinant has already converted something other than a variable name, then print just as
if (oldDet.firstChild.wholeText.includes("\\begin")) {
newDet = createHTMLNodesFromString(((writeDet) ? "\\det" : "") + oldDet.innerHTML);
} else {
//Else use determinant as function instead of bracket notation defined in matrix tags
newDet = createHTMLNodesFromString("\\det\\left(" + oldDet.innerHTML + "\\right)");
}
oldDet.replaceWith(...newDet);
}
while (dom.querySelector("sup") != undefined) {
var oldSUP = dom.querySelector("sup");
var newSUP = createHTMLNodesFromString("^{" + oldSUP.innerHTML + "}");
oldSUP.replaceWith(...newSUP);
//console.log(dom.innerHTML)
}
//Replace sub{} with _{}
while (dom.querySelector("sub") != undefined) {
var oldSUB = dom.querySelector("sub");
var newSUB = createHTMLNodesFromString("_{" + oldSUB.innerHTML + "}");
oldSUB.replaceWith(...newSUB);
//console.log(dom.innerHTML)
}
//Replace var with nothing since MathJax automatically styles text
while (dom.querySelector("var") != undefined) {
var oldVAR = dom.querySelector("var");
var newVAR = createHTMLNodesFromString("{" + oldVAR.innerHTML + "}");
oldVAR.replaceWith(...newVAR);
//console.log(dom.innerHTML)
}
while (dom.querySelector("text") != undefined) {
var oldText = dom.querySelector("text");
var newText = createHTMLNodesFromString("\\text{" + oldText.innerHTML + "}");
oldText.replaceWith(...newText);
}
var otherFunctions = ["sin", "cos", "tan", "csc", "sec", "cot", "ln"];
for (var i = 0; i < otherFunctions.length; i++) {
while (dom.querySelector(otherFunctions[i]) != undefined) {
var oldFunc = dom.querySelector(otherFunctions[i]);
var powerStr = "";
if (oldFunc.getAttribute("inv") != null) {
powerStr = "^{-1}";
} else if (oldFunc.getAttribute("power")) {
powerStr = "^{" + oldFunc.getAttribute("power") + "}";
}
var newFunc = createHTMLNodesFromString("\\operatorname{" + otherFunctions[i] + "}" + powerStr + "{\\left(" + oldFunc.innerHTML + "\\right)}");
oldFunc.replaceWith(...newFunc);
}
}
//Replace vector{} with \overrightarrow{}
while (dom.querySelector("vector") != undefined) {
var oldVector = dom.querySelector("vector");
var newVector = createHTMLNodesFromString("\\overrightarrow{" + oldVector.innerHTML + "}");
oldVector.replaceWith(...newVector);
}
while (dom.querySelector("magnitude") != undefined) {
var oldMagnitude = dom.querySelector("magnitude");
var newMagnitude = createHTMLNodesFromString("\\left\\vert\\left\\vert" + oldMagnitude.innerHTML + "\\right\\vert\\right\\vert");
oldMagnitude.replaceWith(...newMagnitude);
}
//Remember that MathJax does not support boxed answers in aligned equations
while (dom.querySelector("span.answer") != undefined) {
var oldSpan = dom.querySelector("span.answer");
//\llap{\mathrel{\boxed{\phantom{3x = 19 - 2y}}}}
var newSpan = createHTMLNodesFromString("\\boxed{" + oldSpan.innerHTML + "}");
oldSpan.replaceWith(...newSpan);
}
while (dom.querySelector("span.cancel") != undefined) {
var oldSpan = dom.querySelector("span.cancel");
var newSpan = createHTMLNodesFromString("\\cancel{" + oldSpan.innerHTML + "}");
oldSpan.replaceWith(...newSpan);
}
//Remember that this tag does not like a verbose usage of <var></var> inside of it, try to remove unnecessary brackets in the event of "Misplaced &"
while (dom.querySelector("span.alignedEquations") != undefined) {
var oldSpanAlignedEquations = dom.querySelector("span.alignedEquations");
while (oldSpanAlignedEquations.querySelector("br") != undefined) {
var oldBR = oldSpanAlignedEquations.querySelector("br");
var newBR = createHTMLNodesFromString("\n\\\\\n");
oldBR.replaceWith(...newBR);
}
oldSpanAlignedEquations.innerHTML = oldSpanAlignedEquations.innerHTML.replace(/=/g, "&=").replace(/\-\>/gm, "&->").replace(/\->/gm, "&->");
var newSpanAlignedEquations = createHTMLNodesFromString("\\begin{align}" + oldSpanAlignedEquations.innerHTML + "\\end{align}");
oldSpanAlignedEquations.replaceWith(...newSpanAlignedEquations);
}
//Used to simply get rid of all other span tags until new fixes can be implemented
while (dom.querySelector("span") != undefined) {
var oldSpan = dom.querySelector("span");
var newSpan = createHTMLNodesFromString(oldSpan.innerHTML);
oldSpan.replaceWith(...newSpan);
}
//myString.replace(/<sup>()<\/sup>/, "^{$1}");
innerMath += dom.innerHTML.replaceAll(",", ",\\,"); //adds a space after every comma - Added it down here since my matrix tags used commas and I didn't want to replace those until they were latex-ified
innerMath += "\\)";
equationTag.innerHTML = innerMath;
//Use for debugging purposes:
equationTag.setAttribute("LaTeX", innerMath);
});
/* Technically now useless block of code since it typesets automatically
try {
//MathJax.typesetPromise();
} catch (err) {
console.warn("MathJax not yet supported on this page. Error:\n" + err);
}
*/
}
//Replaced/Defined all math function
//Defined all Sqrt Tags
var sqrtTags = document.querySelectorAll(parentElement + "sqrt");
for (var e = 0; e < sqrtTags.length; e++) {
var sqrtInput = sqrtTags[e].innerHTML;
sqrtTags[e].innerHTML = "√<span style='border-top: 0.5px solid;'>" + sqrtInput + "</span>";
}
//Defined all Limit Tags
var limTags = document.querySelectorAll(parentElement + "lim");
for (var f = 0; f < limTags.length; f++) {
var limAs = limTags[f].getAttribute("as");
var limApproaches = limTags[f].getAttribute("approaches");
limTags[f].innerHTML = "<div class='fraction'><div class='top'><var>lim</var></div><div class='bottom'><var>" + limAs + "</var>→" + limApproaches + "</div></div>";
}
//Defined trig tags
var sinTags = document.querySelectorAll("sin");
for (var j = 0; j < sinTags.length; j++) {
var sinInput = sinTags[j].innerHTML;
sinTags[j].innerHTML = "sin(<var>" + sinInput + "</var>)";
}
var cosTags = document.querySelectorAll(parentElement + "cos");
for (var k = 0; k < cosTags.length; k++) {
var cosInput = cosTags[k].innerHTML;
cosTags[k].innerHTML = "cos(<var>" + cosInput + "</var>)";
}
var tanTags = document.querySelectorAll(parentElement + "tan");
for (var l = 0; l < tanTags.length; l++) {
var tanInput = tanTags[l].innerHTML;
tanTags[l].innerHTML = "tan(<var>" + tanInput + "</var>)";
}
var cscTags = document.querySelectorAll(parentElement + "csc");
for (var m = 0; m < cscTags.length; m++) {
var cscInput = cscTags[m].innerHTML;
cscTags[m].innerHTML = "csc(<var>" + cscInput + "</var>)";
}
var secTags = document.querySelectorAll(parentElement + "sec");
for (var n = 0; n < secTags.length; n++) {
var secInput = secTags[n].innerHTML;
secTags[n].innerHTML = "sec(<var>" + secInput + "</var>)";
}
var cotTags = document.querySelectorAll(parentElement + "cot");
for (var o = 0; o < cotTags.length; o++) {
var cotInput = cotTags[o].innerHTML;
cotTags[o].innerHTML = "cot(<var>" + cotInput + "</var>)";
}
//Defined LaPlaceTransform tags
var laPlaceTransformTags = document.querySelectorAll(parentElement + "laPlaceTransform");
for (var t = 0; t < laPlaceTransformTags.length; t++) {
var laPlaceTransformInput = laPlaceTransformTags[t].innerHTML;
laPlaceTransformTags[t].innerHTML = "ℒ{<var>" + laPlaceTransformInput + "</var>}";
}
var invLaPlaceTransformTags = document.querySelectorAll(parentElement + "invLaPlaceTransform");
for (var t = 0; t < invLaPlaceTransformTags.length; t++) {
var invLaPlaceTransformInput = invLaPlaceTransformTags[t].innerHTML;
invLaPlaceTransformTags[t].innerHTML = "ℒ<sup>−1</sup>{<var>" + invLaPlaceTransformInput + "</var>}";
}
//Defined log tag and ln tag
var logTags = document.querySelectorAll(parentElement + "log");
for (var p = 0; p < logTags.length; p++) {
var logInput = logTags[p].innerHTML;
var base = logTags[p].getAttribute("base");
//If there are elements or compounds in the tag, don't italicize by default
if (logTags[p].querySelectorAll("compound, element").length > 0) {
if (base !== null) {
var base = logTags[p].getAttribute("base");
logTags[p].innerHTML = "log<sub>" + base + "</sub>(" + logInput + ")";
} else {
logTags[p].innerHTML = "log(" + logInput + ")";
}
} else {
if (base !== null) {
var base = logTags[p].getAttribute("base");
logTags[p].innerHTML = "log<sub>" + base + "</sub>(<var>" + logInput + "</var>)";
} else {
logTags[p].innerHTML = "log(<var>" + logInput + "</var>)";
}
}
}
var lnTags = document.querySelectorAll(parentElement + "ln");
for (var q = 0; q < lnTags.length; q++) {
var lnInput = lnTags[q].innerHTML;
//If there are elements or compounds in the tag, don't italicize by default
if (lnTags[p].querySelectorAll("compound, element").length > 0) {
lnTags[q].innerHTML = "ln(" + lnInput + ")";
} else {
lnTags[q].innerHTML = "ln(<var>" + lnInput + "</var>)";
}
}
//Defined Derivative Tags (Will need to be changed further as we learn new concepts)
//<nDeriv of="f" respectTo="t"></nDeriv> === df/dt
var derivativeTags = document.querySelectorAll(parentElement + "derivative");
for (var r = 0; r < derivativeTags.length; r++) {
var derivativeOf = derivativeTags[r].getAttribute("of") ? derivativeTags[r].getAttribute("of") : "";
var derivativeRespectTo = derivativeTags[r].getAttribute("respectTo") ? derivativeTags[r].getAttribute("respectTo") : "x";
var derivativeOrder = derivativeTags[r].getAttribute("order") ? "<sup>" + derivativeTags[r].getAttribute("order") + "</sup>" : "";
derivativeTags[r].innerHTML = "<div class='fraction'><div class='top'>d" + derivativeOrder + "<var>" + derivativeOf + "</var></div><div class='bottom'>d<var>" + derivativeRespectTo + "</var>" + derivativeOrder + "</div></div>";
}
var pDerivativeTags = document.querySelectorAll(parentElement + "pDerivative");
for (var s = 0; s < pDerivativeTags.length; s++) {
var pDerivativeOf = pDerivativeTags[s].getAttribute("of") ? pDerivativeTags[s].getAttribute("of") : "";
var pDerivativeRespectTo = pDerivativeTags[s].getAttribute("respectTo") ? pDerivativeTags[s].getAttribute("respectTo") : "x";
var pDerivativeOrder = pDerivativeTags[s].getAttribute("order") ? "<sup>" + pDerivativeTags[s].getAttribute("order") + "</sup>" : "";
pDerivativeTags[s].innerHTML = "<div class='fraction'><div class='top'>∂" + pDerivativeOrder + "<var>" + pDerivativeOf + "</var></div><div class='bottom'>∂<var>" + pDerivativeRespectTo + "</var>" + pDerivativeOrder + "</div></div>";
}
var integralTags = document.querySelectorAll(parentElement + "integral");
for (var h = 0; h < integralTags.length; h++) {
integralTags[h].classList.add("notYetStyled")
}
var integralTags = document.querySelectorAll(parentElement + "integral");
while (document.querySelector(parentElement + "integral.notYetStyled") != undefined) {
var integralTag = document.querySelector(parentElement + "integral.notYetStyled");
var lowerBound = integralTag.getAttribute("lowerBound");
var upperBound = integralTag.getAttribute("upperBound");
var respectTo = integralTag.getAttribute("respectTo");
var span = document.createElement("span");
span.innerHTML = "<var>d" + respectTo + "</var>";
if (lowerBound !== null || upperBound !== null) {
integralTag.innerHTML = "<span style='font-size: 200%; display: inline-block; transform: translateY(10px);'>∫</span><sub style='display: inline-block; transform: translateY(12px);'>" + lowerBound + "</sub><sup style='display: inline-block; transform: translateY(-11px);'>" + upperBound + "</sup><span style='transform: translateY(50px);'>" + integralTag.innerHTML + "</span>";
} else {
integralTag.innerHTML = "<span style='font-size: 200%; display: inline-block; transform: translateY(10px);'>∫</span><span style='transform: translateY(50px);'>" + integralTag.innerHTML + "</span>";
}
console.log(integralTag.parentNode);
integralTag.parentNode.insertBefore(span, integralTag.nextSibling);
integralTag.classList.remove("notYetStyled");
}
/*
for (var h = 0; h < integralTags.length; h++) {
console.log(integralTags[h]);
var lowerBound = integralTags[h].getAttribute("lowerBound");
var upperBound = integralTags[h].getAttribute("upperBound");
var respectTo = integralTags[h].getAttribute("respectTo");
var span = document.createElement("span");
span.innerHTML = "<var>d" + respectTo + "</var>";
}
*/
var evaluatedTags = document.querySelectorAll(parentElement + "evaluated");
for (var t = 0; t < evaluatedTags.length; t++) {
var from = evaluatedTags[t].getAttribute("from");
var to = evaluatedTags[t].getAttribute("to") == null ? "" : evaluatedTags[t].getAttribute("to");
evaluatedTags[t].innerHTML = "<table style='display: inline-table; border-left: 2px solid black; padding:0; border-collapse: collapse; transform: translate(0, -5px);'><tr><td style='transform: translate(0, -10px);'>" + to + "</td></tr><tr><td style='transform: translate(0, 10px)'>" + from + "</td></tr></table>";
}
//Defined matrix tag
//<matrix dimensionX="3" dimensionY="3" values="1, 2, 3, 4, 5, 6, 7, 8, 9"></matrix>
var matrixTags = document.querySelectorAll(parentElement + "matrix");
for (var u = 0; u < matrixTags.length; u++) {
var dimensionX = parseInt(matrixTags[u].getAttribute("dimensionX"));
var dimensionY = parseInt(matrixTags[u].getAttribute("dimensionY"));
var values = matrixTags[u].getAttribute("values").split(", ");
//var values = matrixTags[u].innerHTML.split(", ");
if (values.length !== dimensionX * dimensionY) {
console.log(values);
matrixTags[u].innerHTML = "Could not display matrix, Dimension Error";
} else {
var table = document.createElement("table");
table.classList.add("matrix");
for (var row = 0; row < dimensionY; row++) {
var tr = document.createElement("tr");
for (var col = 0; col < dimensionX; col++) {
var td = document.createElement("td");
td.innerHTML = values[row * dimensionX + col];
tr.appendChild(td);
}
table.appendChild(tr);
}
matrixTags[u].appendChild(table);
}
}
//Defined vector tag
var vectorTags = document.querySelectorAll(parentElement + "vector");
for (var i = 0; i < vectorTags.length; i++) {
var vectorName = vectorTags[i].innerHTML;
vectorTags[i].innerHTML = '<div class="outer"><div class="inner"><var>→</var></div><div class="inner"><var>' + vectorName + '</var></div></div>';
}
//Added Sigma tags
var sigmaTags = document.querySelectorAll(parentElement + "sigma");
for (var r = 0; r < sigmaTags.length; r++) {
var startValue = sigmaTags[r].getAttribute("start");
var endValue = (sigmaTags[r].getAttribute("end") !== null) ? sigmaTags[r].getAttribute("end") : "";
var sigmaInnerHTML = sigmaTags[r].innerHTML;
sigmaTags[r].innerHTML = "<table class='sigmaTag' style='display: inline-table; transform: translateY(-30%);'><tr><td>" + endValue + "</td></tr><tr><td style='font-size: 200%;'>Σ</td><td>" + sigmaInnerHTML + "</td></tr><tr><td>" + startValue + "</td></tr></table>";
}
var renderJS = document.querySelectorAll(parentElement + "script.renderJS");
renderJS.forEach((script) => {
//console.log(script.innerHTML == "");
if (script.innerHTML == "" && script.hasAttribute("src")) {
//If the inner body is empty but I have provided an SRC (meaning that it is probably one of those auto-generated drawing scripts)
//Then fetch the script and run it manually
fetch(script.getAttribute("src")).then((response) => response.text()).then((jsCode) => {
eval(jsCode);
});
} else {
//Else just evaluate whatever is inside the script
eval(script.innerHTML);
}
});
//Room for science stuff:
/*
If there are element tags, make sure the file is downloaded before you proceed.
if not, then proceed to renderScience anyways, since there is an `if` block there
that conditionally uses the periodicTableOfElements.json file depending on whether
or not there are any element tags, because the funciton still has other science tags
to render
*/
var elementTags = document.querySelectorAll(parentElement + "element");
if (elementTags.length > 0) {
//If there is no periodic table saved in local storage
if (!localStorage.getItem("periodicTable")) {
var makeRequest = function(url, httpMethod) {
//Load the file
var fileRequest = new XMLHttpRequest();
return new Promise((resolve, reject) => {
/*fileRequest.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
resolve(fileRequest);
} else {
reject({
status: fileRequest.status,
statusText: fileRequest.statusText
});
}
}*/
fileRequest.onload = function() {
if (this.readyState == 4 && this.status == 200) {
resolve(fileRequest);
} else {
reject(fileRequest);
}
}
fileRequest.open(httpMethod || "GET", url, true);
fileRequest.send();
});
}
makeRequest("../periodicTableOfElements.json", "GET").then((xhr) => {
//Set the data to localStorage for next time usage
localStorage.setItem("periodicTable", xhr.responseText);
console.log("{");
for (var prop in xhr) {
console.log(`${prop}: ${xhr[prop]}`);
}
console.log("}");
console.log("Success");
renderScience(parentElement);
}).catch((error) => {
console.log("{");
for (var prop in error) {
console.log(`${prop}: ${error[prop]}`);
}
console.log("}");
console.log(error);
alert("Sorry but elements cannot be shown at this time");
});
} else {
//Already stored in localStorage, carry on
renderScience(parentElement);
}
} else {
renderScience(parentElement);
}
}
/*
Periodic Table Data Found At https://github.com/andrejewski/periodic-table/blob/master/data.json
Code below to remove unnecessary information to save space and loading time
var oldListOfElements = [];
var newListOfElements = oldListOfElements.map(
function (oldElement) {
var newElement = oldElement;
delete newElement.cpkHexColor;
delete newElement.standardState;
delete newElement.meltingPoint;
delete newElement.standardState;
delete newElement.boilingPoint;
delete newElement.density;
delete newElement.ionRadius;
delete newElement.atomicRadius;
delete newElement.bondingType;
delete newElement.yearDiscovered;
delete newElement.vanDelWaalsRadius;
delete newElement.electronAffinity;
newElement.atomicMass = (newElement.symbol == "H") ? Number(parseFloat(String(oldElement.atomicMass).replace("[", "").replace("]", "")).toFixed(3)) : Number(parseFloat(String(oldElement.atomicMass).replace("[", "").replace("]", "")).toFixed(2)) //If Hydrogen, round to 3 decimal places, else round to 2
newElement.oxidationStates = (String(oldElement.oxidationStates) != "") ? String(oldElement.oxidationStates).split(", ").map((el) => parseInt(el)) : null; //Convert the oxidation states list to an array from a CSV string if it is not empty
newElement.electronicConfiguration = (oldElement.electronicConfiguration != "") ? oldElement.electronicConfiguration.split(" ").map((el) => { return el.replace(/(?<=[a-z])(\d{1,2})/gi, "<sup>$1</sup>")}).join(" ") : ""; //If it is not empty, take the electron configuration and make all the last numbers into powers, else leave it empty
return newElement;
}
);*/
function renderScience(parentElement = "") {
//Defined elementTag
var elementTags = document.querySelectorAll(parentElement + "element");
if (elementTags.length > 0) {
//<element name="F" atomicNumber massNumber electronConfiguration charge="2−" oxidationNumber="+1" number="2"></element>
var periodicTable = JSON.parse(localStorage.getItem("periodicTable"));
//console.log(periodicTable);
var listOfPeriodicElements = periodicTable.map((el) => { return el.symbol; });
//console.log(listOfPeriodicElements);
function getPeriodicElementByName(name) {
//Quickest way to search through 118 elements for element
/*
Search through array of listOfPeriodicElements for index
and use the same index on other array, that way I am not
searching through the entire array of objects
*/
var index = listOfPeriodicElements.indexOf(name);
return (index > -1) ? periodicTable[index] : null; //If not found in index then just return a null value
}
elementTags.forEach((elementTag) => {
var name = elementTag.getAttribute("name");
var elementInQuestion = (name == "α") ? getPeriodicElementByName("He") : getPeriodicElementByName(name); //If alpha particle, use Helium properties, else use element properties
var electronicConfiguration = elementTag.getAttribute("electronConfiguration");
var fullElectronicConfiguration = elementTag.getAttribute("fullElectronConfiguration");
var massNumber = elementTag.getAttribute("massNumber");
var atomicNumber = elementTag.getAttribute("atomicNumber");
var number = elementTag.getAttribute("number");
var charge = elementTag.getAttribute("charge");
var oxidationNumber = elementTag.getAttribute("oxidationState");
var elementTaginnerHTML = "";
if (electronicConfiguration !== null) {
if (electronicConfiguration == "") {
elementTaginnerHTML = elementInQuestion.electronicConfiguration;
} else {
elementTaginnerHTML = electronicConfiguration.split(" ").map((el) => { return el.replace(/(?<=[a-z])(\d{1,2})/gi, "<sup>$1</sup>") }).join(" ");
}
} else if (fullElectronicConfiguration !== null) {
if (fullElectronicConfiguration == "") {
//Recursively get the electron configurations of all the electrons - since it only comes in noble gas form
function getFullElectronConfiguration(abbreviatedElectronConfiguration) {
var returnVal = abbreviatedElectronConfiguration;
if (abbreviatedElectronConfiguration.includes("[")) {
var regex = /\[([A-Za-z]{1,2})\]/;
var newElementInQuestion = regex.exec(abbreviatedElectronConfiguration)[1];
//var newElementInQuestion = abbreviatedElectronConfiguration.split("]")[0].split("[")[1];
var newElementInQuestionElectronConfiguration = getPeriodicElementByName(newElementInQuestion).electronicConfiguration;
returnVal = abbreviatedElectronConfiguration.replace(/\[[A-Za-z]{1,2}\]/, newElementInQuestionElectronConfiguration);
if (returnVal.includes("[")) {
return getFullElectronConfiguration(returnVal);
} else {
return returnVal;
}
} else {
return returnVal;
}
}
elementTaginnerHTML = getFullElectronConfiguration(elementInQuestion.electronicConfiguration);
} else {
elementTaginnerHTML = fullElectronicConfiguration;
}
} else {
var massNumberText = () => {
//If massNumber is not requested, leave it blank
if (massNumber == null) {
return "";
}
//If massnumber is requested but not provided, use the dictionary one
else if (massNumber == "") {
return (elementInQuestion.atomicMass).toFixed(0);
}
/*
If massNumber is neither of the above, it must be provided
so just use the provided value
*/
else {
return massNumber;
}
};
var chargeOrOxidationNumberText = () => {
//Choose between whether to show charge, oxidation number, or neither
if (charge == null || charge == "" || charge == undefined) {
//If charge is not provided, check if oxidation is
if (oxidationNumber == null || oxidationNumber == "" || oxidationNumber == undefined) {
return ""; //Do nothing
} else if (oxidationNumber !== null && oxidationNumber !== "" && oxidationNumber !== undefined) {
return oxidationNumber;
}
}
//If neither is true, charge must be a value
else if (charge !== null && charge !== "" && charge !== undefined) {
return charge;
}
//If nothing is provided, leave this box empty
else {
return "";
}
};
var atomicNumberText = () => {
//If atomicNumber is not requested, leave it blank
if (atomicNumber == null) {
return "";
}
//If atomicnumber is requested but not provided, use the dictionary one
else if (atomicNumber == "") {
return elementInQuestion.atomicNumber;
}
/*
If atomicNumber is neither of the above, it must be provided
so just use the provided value
*/
else {
return atomicNumber;
}
};
var numericAmountText = () => {
//If number is not requested, or not provided with a value, leave it blank
if (number == null || number == "") {
return "";
}
/*
If number is neither of the above, it must be provided
so just use the provided value
*/
else {
return number;
}
};
elementTaginnerHTML = `<table class="chemicalElement">
<!--Upper Row-->
<tr>
<td style='text-align: right;'>${massNumberText()}</td><td></td><td style='text-align: left;'>${chargeOrOxidationNumberText()}</td>
</tr>
<!--Main Row-->
<tr>
<td></td>
<td class='elementName'>${/*Name will always be provided*/name}</td>
</tr>
<!--Lower Row-->
<tr>
<td style='text-align: right;'>${atomicNumberText()}</td><td></td><td style='text-align: left;'>${numericAmountText()}</td>
</tr>
</table>`;
}
elementTag.innerHTML = elementTaginnerHTML;
});
}
/*Try combining the element and compound tags*/
//Defined compound tag - <compound>5C6H12O6^-7</compound>
var compoundTags = document.querySelectorAll(parentElement + "compound");
for (var i = 0; i < compoundTags.length; i++) {
var compound = compoundTags[i].innerHTML;
var stateOfMatter = compoundTags[i].getAttribute("state");
//The first RegExp takes care of subscripts, looks for 1-2 numbers found after a letter or parenthesis (like `(OH)2`)
//The second RegExp looks for the ^ sign and makes 1-3 characters after it into a superscript (for ions)
compound = compound.replace(/(?<=[A-Za-z\)])(\d{1,2})/g, "<sub>$1</sub>").replace(/\^([\d+-]{1,3})/g, "<sup>$1</sup>").replace("-", "−");
compoundTags[i].innerHTML = (stateOfMatter != undefined && stateOfMatter != "") ? compound + " (<var>" + stateOfMatter + "</var>)" : compound;
}
}
function toggleDiv(id) {
var element = document.querySelector(id);
if (element.style.display === "block") {
element.style.display = "none";
document.querySelector(id + "ToggleButton").innerHTML = "+";
} else {
element.style.display = "block";
document.querySelector(id + "ToggleButton").innerHTML = "−";
}
}
function toggleSolution(id, proof) {
var element = document.querySelector(id);
if (element.style.display === "block") {
element.style.display = "none";
if (typeof proof != typeof "") {
document.querySelector(id + "ToggleLink").innerHTML = (proof == true) ? "Show Proof" : "Show Solution";
} else {
document.querySelector(id + "ToggleLink").innerHTML = "Show " + proof;
}
} else {
element.style.display = "block";
if (typeof proof != typeof "") {
document.querySelector(id + "ToggleLink").innerHTML = (proof == true) ? "Hide Proof" : "Hide Solution";
} else {
document.querySelector(id + "ToggleLink").innerHTML = "Hide " + proof;
}
}
}
/*Extra Tools:*/
// https://stackoverflow.com/questions/34506036/how-do-i-draw-thin-but-sharper-lines-in-html-canvas
// Use to make canvas lines clearer on-screen
function oversampleCanvas(tgtCanvas, ctx, factor) {
if (!tgtCanvas.classList.contains("alreadyOversampled")) {
var width = tgtCanvas.width;
var height = tgtCanvas.height;
tgtCanvas.width = Math.trunc(width * factor);
tgtCanvas.height = Math.trunc(height * factor);
tgtCanvas.style.width = width + 'px';
tgtCanvas.style.height = height + 'px';
ctx.scale(factor, factor);
tgtCanvas.classList.add("alreadyOversampled");
}
}
function drawArrow(context, fromx, fromy, tox, toy, extraArgs) {
//variables to be used when creating the arrow
var headlen = 10;
var angle = Math.atan2(toy - fromy, tox - fromx);
//starting path of the arrow from the start square to the end square and drawing the stroke
context.beginPath();
context.setLineDash([]);
if (extraArgs !== undefined) {
if (extraArgs.lineDash !== undefined) {
context.setLineDash(extraArgs.lineDash);
}
if (extraArgs.color !== undefined) {
context.fillStyle = extraArgs.color;
context.strokeStyle = extraArgs.color;
}
if (extraArgs.headlen !== undefined) {
headlen = extraArgs.headlen;
}
}
context.moveTo(fromx, fromy);
context.lineTo(tox, toy);
context.stroke();
context.setLineDash([]);
//starting a new path from the head of the arrow to one of the sides of the point
context.beginPath();
context.moveTo(tox, toy);
context.lineTo(tox - headlen * Math.cos(angle - Math.PI / 7), toy - headlen * Math.sin(angle - Math.PI / 7));
//path from the side point of the arrow, to the other side point
context.lineTo(tox - headlen * Math.cos(angle + Math.PI / 7), toy - headlen * Math.sin(angle + Math.PI / 7));
//path from the side point back to the tip of the arrow, and then again to the opposite side point
context.lineTo(tox, toy);
context.lineTo(tox - headlen * Math.cos(angle - Math.PI / 7), toy - headlen * Math.sin(angle - Math.PI / 7));
//draws the paths created above
context.stroke();
context.fill();
}
// returns radians
function findAngle(sx, sy, ex, ey) {
// make sx and sy at the zero point
return Math.atan2((ey - sy), (ex - sx));
}
//Taken from above
function drawArrowhead(ctx, locx, locy, angle, sizex, sizey) {
var hx = sizex / 2;
var hy = sizey / 2;
ctx.translate((locx), (locy));
ctx.rotate(angle);
ctx.translate(-hx, -hy);
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(0, 1 * sizey);
ctx.lineTo(1 * sizex, 1 * hy);
ctx.closePath();
ctx.fill();
ctx.translate(hx, hy);
ctx.rotate(-angle);
ctx.translate(-locx, -locy);
}
/*
The below function is stolen directly from https://stackoverflow.com/questions/11217374/html5-render-simple-electrical-circuits
And modified for personal use
- This class draws circuits in the conventional method of current, positive to negative
All the methods return the CircuitDiagram object itself, allowing for event chaining