EN
JavaScript - Math.atan() method example
16 points
The Math.atan
function returns number in radians in the range -Math.PI/2
to +Math.PI/2
. The function calculates the inverted tangent function value.
xxxxxxxxxx
1
function calculateAngle(a, b) {
2
return Math.atan(a / b);
3
}
4
5
/*
6
|\
7
| \ h - for this function this information is not necessary
8
a | \
9
|__*\ <- angle
10
b
11
*/
12
13
var a, b;
14
15
// a and b build isosceles right triangle
16
a = 3;
17
b = a;
18
console.log( calculateAngle(a, b) ); // 0.7853981633974483 <- ~45 degrees
19
20
// a and b build half of equilateral triangle
21
a = 3;
22
b = a * Math.sqrt(3);
23
console.log( calculateAngle(a, b) ); // 0.5235987755982988 <- ~30 degrees
24
25
// a and b build very high (+Inf) and slim (~0) triangle
26
a = +Infinity;
27
b = 0;
28
console.log( calculateAngle(a, b) ); // 1.5707963267948966 <- ~90 degrees
Syntax | Math.atan(number) |
Parameters |
|
Result |
If value can not be calculated |
Description |
|
xxxxxxxxxx
1
function calculateAngle(a, b) {
2
var angle = Math.atan(a / b);
3
4
return (180 / Math.PI) * angle; // rad to deg conversion
5
}
6
7
/*
8
|\
9
| \ h - for this function this information is not necessary
10
a | \
11
|__*\ <- angle
12
b
13
*/
14
15
var a, b;
16
17
// a an b build isosceles right triangle
18
a = 3;
19
b = a;
20
console.log( calculateAngle(a, b) ); // ~45 degrees
21
22
// a and b build half of equilateral triangle
23
a = 3;
24
b = a * Math.sqrt(3);
25
console.log( calculateAngle(a, b) ); // ~30 degrees
26
27
// a and b build very high (+Inf) and slim (~0) triangle
28
a = +Infinity;
29
b = 0;
30
console.log( calculateAngle(a, b) ); // ~90 degrees
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style> #canvas { border: 1px solid black; } </style>
5
</head>
6
<body>
7
<canvas id="canvas" width="400" height="150"></canvas>
8
<script>
9
10
var canvas = document.querySelector('#canvas');
11
var context = canvas.getContext('2d');
12
13
// arctangent chart range
14
var x1 = -10.0;
15
var x2 = +10.0;
16
var y1 = -Math.PI / 2;
17
var y2 = +Math.PI / 2;
18
19
var dx = 0.1;
20
21
var xRange = x2 - x1;
22
var yRange = y2 - y1;
23
24
function calculatePoint(x) {
25
var y = Math.atan(x);
26
27
// chart will be reversed horizontaly because of reversed canvas pixels
28
29
var nx = (x - x1) / xRange; // normalized x
30
var ny = 1.0 - (y - y1) / yRange; // normalized y
31
32
var point = {
33
x: nx * canvas.width,
34
y: ny * canvas.height
35
};
36
37
return point;
38
}
39
40
console.log('x range: <' + x1 + '; ' + x2 + '>');
41
console.log('y range: <' + y1 + '; ' + y2 + '> // angles in radians');
42
43
var point = calculatePoint(x1);
44
45
context.beginPath();
46
context.moveTo(point.x, point.y);
47
48
for (var x = x1 + dx; x < x2; x += dx) {
49
point = calculatePoint(x);
50
context.lineTo(point.x, point.y);
51
}
52
53
point = calculatePoint(x2);
54
context.lineTo(point.x, point.y);
55
context.stroke();
56
57
</script>
58
</body>
59
</html>