-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
107 lines (84 loc) · 2.54 KB
/
script.js
File metadata and controls
107 lines (84 loc) · 2.54 KB
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
//describe buttons
document.getElementById("sinXButton").onclick = function() {return draw(sinX)};
document.getElementById("cosXButton").onclick = function() {return draw(cosX)};
document.getElementById("simpleXButton").onclick = function() {return draw(simpleX)};
document.getElementById("squareXButton").onclick = function() {return draw(squareX)};
document.getElementById("expXButton").onclick = function() {return draw(expX)};
document.getElementById("lnXButton").onclick = function() {return draw(lnX)};
var canvas = document.getElementById("graphics");
init(canvas, canvas.getContext("2d"))
//start drawing
function draw(func) {
var canvas = document.getElementById("graphics");
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
init(canvas, ctx);
drawFunction(ctx, canvas, func);
}
//draw exact function
function drawFunction(ctx, canvas, func) {
var xx, yy;
var dx = 0.05;
var x0 = 0.5 + 0.5 * canvas.width;
var y0 = 0.5 + 0.5 * canvas.height;
var scale = 20;
var iMax = Math.round((ctx.canvas.width - x0) / dx);
var iMin = Math.round(-x0 / dx);
ctx.beginPath();
ctx.lineWidth = 1.5;
ctx.strokeStyle = "rgb(66,44,255)";
for (var i = iMin; i <= iMax; i++) {
xx = dx * i;
yy = scale * func(xx / scale);
if (i == iMin) {
ctx.moveTo(x0 + xx, y0 - yy);
} else {
ctx.lineTo(x0 + xx, y0 - yy);
}
}
ctx.stroke();
}
//draw axes
function init(canvas, ctx) {
ctx.beginPath();
for (var x = 0.5; x < canvas.width; x += 10) {
ctx.moveTo(x, 0);
ctx.lineTo(x, canvas.width);
}
for (var y = 0.5; y < canvas.height; y += 10) {
ctx.moveTo(0, y);
ctx.lineTo(canvas.height, y);
}
ctx.strokeStyle = "#eee";
ctx.stroke();
ctx.beginPath();
ctx.moveTo(0.5 * canvas.width, 0);
ctx.lineTo(0.5 * canvas.width, canvas.height);
ctx.moveTo(0, 0.5 * canvas.height);
ctx.lineTo(canvas.width, 0.5 * canvas.height);
ctx.strokeStyle = "rgb(180, 180, 180)";
ctx.lineWidth = 2;
ctx.stroke();
ctx.font = "15px Arial";
ctx.fillText("x", canvas.width - 10, 0.5 * canvas.height - 5);
ctx.fillText("y", 0.5 * canvas.width + 5, 10);
ctx.fillText("0", 0.5 * canvas.width + 5, 0.5 * canvas.height + 15);
}
function sinX(x) {
return Math.sin(x);
}
function cosX(x) {
return Math.cos(x);
}
function squareX(x) {
return Math.pow(x, 2);
}
function simpleX(x) {
return x;
}
function expX(x) {
return Math.exp(x);
}
function lnX(x) {
return Math.log(x) / Math.log(10);
}