I\'m trying to create a function that draws a triangle in the middle of an HTML canvas based on three given lengths, I thought this would be an easy intro to HTML canvas, I was
Set Ax=0, Ay=0
, set Bx=R3, By=0
. Then the third point satisfies two circle equations
(Cx-Ax)² + (Cy-Ay)² = R2²
(Cx-Bx)² + (Cy-By)² = R1²
which given the chosen coordinates reduce to
Cx² + Cy² = R2²
(Cx-R3)² + Cy² = R1²
and in the difference
2*Cx*R3 = R2²+R3²-R1²
which allows to compute Cx
and from that Cy
.
In code it looks like this:
var canvas = document.getElementById('triangle-canvas');
var ctx = canvas.getContext('2d');
var R1=120, R2=140, R3=90;
var Ax=0, Ay=0;
var Bx=R3, By=0;
var Cx=(R2*R1+R3*R3-R1*R1)/(2*R3);
var Cy=Math.sqrt(R2*R2-Cx*Cx);
var Ox = canvas.width / 2 - Bx/2;
var Oy = canvas.height / 2 + Cy/2;
ctx.beginPath();
ctx.moveTo(Ox+Ax, Oy-Ay);
ctx.lineTo(Ox+Bx, Oy-By);
ctx.lineTo(Ox+Cx, Oy-Cy);
ctx.closePath();
ctx.fillStyle="gold"; ctx.lineWidth=2;
ctx.stroke(); ctx.fill();