How to draw a triangle on three sides JS?

I will have 3 inputs and a button. When you click on this button you should draw a triangle in which the lengths of 3 sides are equal to the values in the inputs. How to organize it? I found this:

context.beginPath();
context.moveTo(30, 20);
context.lineTo(some_value1,some_value2);
context.lineTo(some_value3,some_value4);
context.closePath();

But this method is suitable for drawing, on two sides. I hope now I have described the problem in detail. Thanks in advance.

Upvotes: 0

Views: 1356

Answers (1)

Martin Adámek
Martin Adámek

Reputation: 18429

You will need to compute cartesian coordinates of each point first. You can set the first point to [0, 0], and the second will be at [x1, 0] where x1 is length of first line. Third point needs to be calculated, take a look here how this can be done:

https://math.stackexchange.com/questions/543961/determine-third-point-of-triangle-when-two-points-and-all-sides-are-known

// hardcoded, but you would get those from user
var AB = 40;
var BC = 50;
var AC = 30;

var A = [0, 0]; // starting coordinates
var B = [0, AB];
var C = [];

// calculate third point
C[1] = (AB * AB + AC * AC - BC * BC) / (2 * AB);
C[0] = Math.sqrt(AC * AC - C[1] * C[1]);
console.log(A, B, C);

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

ctx.beginPath();
ctx.moveTo(A[0], A[1]);
ctx.lineTo(B[0], B[1]);
ctx.lineTo(C[0], C[1]);
ctx.fill();
<canvas id="canvas" width="500" height="500"></canvas>

Upvotes: 4

Related Questions