根据三个给定的长度在HTML画布中绘制一个三角形 [英] Draw a triangle in HTML canvas based on three given lenths

查看:94
本文介绍了根据三个给定的长度在HTML画布中绘制一个三角形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个函数,该函数基于三个给定的长度在HTML画布的中间绘制一个三角形,我认为这是HTML画布的简单介绍,我错了.

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 wrong.

这是我到目前为止的位置,但是侧面无法正确渲染:

Here's where I have so far, but the sides aren't rendering properly:

function drawTriangle(sideOne, sideTwo, sideThree) {
    var canvas = document.getElementById('triangle-canvas');
    var ctx = canvas.getContext('2d');

    var cx = canvas.width / 2;
    var cy = canvas.height / 4;

    var sideOneHeight = sideOne * (Math.sqrt(3) / 2);
    var sideTwoHeight = sideTwo * (Math.sqrt(3) / 2);

    ctx.beginPath();
    ctx.moveTo(cx, cy);
    ctx.lineTo(cx + 50, cy + sideOneHeight);
    ctx.lineTo(cx - 50, cy + sideTwoHeight);
    ctx.lineTo(cx, cy);
    ctx.fill();
    ctx.closePath();

}

有什么建议吗?

推荐答案

设置Ax=0, Ay=0,设置Bx=R3, By=0.然后第三点满足两个圆方程

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²

和区别

 2*Cx*R3 = R2²+R3²-R1²

允许从该Cy计算Cx.

在代码中,它看起来像这样:

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

<canvas id='triangle-canvas' height=200 width=400></canvas>

这篇关于根据三个给定的长度在HTML画布中绘制一个三角形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆