-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaxis.js
107 lines (88 loc) · 2.13 KB
/
axis.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
var x_axis = 200;
var y_axis = 200;
var x_max = 3;
var y_max = 3;
var x_scale = x_axis / (x_max + 1);
var y_scale = y_axis / (y_max + 1);
var x_offset = x_axis + 0.5; // location on canvas
var y_offset = y_axis + 0.5; // of graph's origin
var canvas = document.getElementById("axes");
if (canvas.getContext) {
canvas.width = x_axis * 2;
canvas.height = y_axis * 2;
var ctx = canvas.getContext("2d");
drawAxes(ctx);
}
function drawAxes(ctx) {
ctx.font = "20px sans-serif";
ctx.strokeText('0', x_axis - 5, y_axis + 8);
ctx.font = "14px sans-serif";
ctx.strokeText('Y', x_axis - 25, 15);
ctx.strokeText('X', x_axis * 2 - 10, y_axis + 30);
ctx.font = "12px sans-serif";
ctx.lineWidth = 1;
// draw x-axis
ctx.beginPath();
ctx.moveTo(0, y_offset);
ctx.lineTo(x_axis*2, y_offset);
ctx.stroke();
ctx.closePath();
// draw arrow
ctx.beginPath();
ctx.moveTo(x_axis*2+0.5, y_axis+0.5);
ctx.lineTo(x_axis*2+0.5 - 8, y_axis+0.5 - 3);
ctx.lineTo(x_axis*2+0.5 - 8, y_axis+0.5 + 3);
ctx.stroke();
ctx.closePath();
ctx.fill();
// draw x values
j = -x_max;
while (j <= x_max) {
x = j * x_scale;
ctx.strokeStyle = '#aaa';
ctx.beginPath();
ctx.moveTo(x + x_offset, y_offset);
ctx.lineTo(x + x_offset, y_offset + 10);
ctx.stroke();
ctx.closePath();
ctx.strokeStyle = '#666';
ctx.strokeText(j, x + x_offset - 5, y_offset + 30);
j++;
if (j == 0) { j++; }
}
// draw y-axis
ctx.beginPath();
ctx.moveTo(x_offset, 0);
ctx.lineTo(x_offset, y_axis*2);
ctx.stroke();
ctx.closePath();
// draw arrow
ctx.beginPath();
ctx.moveTo(x_axis+0.5, 0.5);
ctx.lineTo(x_axis+0.5 - 3, 0.5 + 8);
ctx.lineTo(x_axis+0.5 + 3, 0.5 + 8);
ctx.stroke();
ctx.closePath();
ctx.fill();
// draw y values
j = -y_max;
while (j <= y_max) {
y = j * y_scale;
ctx.strokeStyle = '#aaa';
ctx.beginPath();
ctx.moveTo(x_offset, y + y_offset);
ctx.lineTo(x_offset - 10, y + y_offset);
ctx.stroke();
ctx.closePath();
ctx.strokeStyle = '#666';
ctx.strokeText(-j, x_offset - 25, y + y_offset + 5);
j++;
if (j == 0) { j++; }
}
}
function offsetX(v) {
return x_offset + (v * x_scale);
}
function offsetY(v) {
return y_offset - (v * y_scale);
}