Draw a triangle in HTML canvas based on three given lenths

前端 未结 2 1094
野的像风
野的像风 2021-01-24 15:06

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

2条回答
  •  没有蜡笔的小新
    2021-01-24 15:31

    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();

提交回复
热议问题