如何在html画布上找到三角形的面积?

时间:2019-12-06 15:56:37

标签: javascript html css html5-canvas

所以我画了一个矩形。

当用户单击画布上的任意位置时,我希望以三角形的形式确定正方形的顶部两个角点的区域以及鼠标单击的坐标。

我已经搜索了三角形面积的公式,并对其进行了多次检查,并确定它的正确性。只是不起作用。

我正在使用:|(Ax(By-Cy)+ Bx(Cy-Ay)+ Cx(Ay-By))/ 2 |

当用户在正方形内单击时,三角形的面积在数值上小于正方形的面积时,我会知道的。唯一的问题是它实际上会变得更大,而且我不确定如何从此处继续。

试图弄清楚,我玩着鼠标坐标并从中减去。这样产生的结果类似于我想要的结果,但是我知道这不是我要确定的三角形的精确区域

如果有人对此有任何见解,将不胜感激。 enter image description here

window.onload =()=>{
    const canvas = document.getElementById("canvas");
    const ctx = canvas.getContext("2d");
   
   
 const getMousePos =(evt) =>{
        let rect = canvas.getBoundingClientRect();
        return {
          x: evt.clientX - rect.left ,
          y: evt.clientY - rect.top 
        };
      }  
   class Button {
  constructor(xPos, yPos, width, height) {
    this.xPos = xPos;
    this.yPos = yPos;
    this.width = width;
    this.height = height;
  }
}
Button.prototype.draw = function (){
    ctx.fillStyle = "#FF0000";
    ctx.fillRect(this.xPos, this.yPos, this.width, this.height);
};   
Button.prototype.area = function (){
    return (this.width * this.height);
};
Button.prototype.sqToTri = function(mousePos) {
    let farX = this.xPos + this.width;
    let farY = this.yPos + this.height;
    
    let upTri = Math.abs(((this.xPos * (mousePos.y - this.yPos)) + (mousePos.x * (this.yPos - this.yPos)) + (farX * (this.yPos - mousePos.y)))/2);
    
    let buttonArea = this.width * this.height;
    
    alert(upTri);
    alert(buttonArea);
}; 
let redButton = new Button(50, 25, 50, 25);
redButton.draw();

       
       
    canvas.addEventListener('click', function(evt) {
        let mousePos = getMousePos( evt);
      
   redButton.sqToTri(mousePos);
      }, false);
      

}
body{
    height:100%;
}
#canvas {
   width: 400px;
  height: 400px;
border: 2px solid black;
  position: absolute;
  top: 20%;
  left: 20%;
}
<!DOCTYPE html>
<html>
	<head>
		<title>Page Title</title>
	</head>
	<body>
	    <div id='containner'>
        <canvas id='canvas'></canvas>
		
		</div>
	</body>
</html>

2 个答案:

答案 0 :(得分:1)

由水平线A,B和任意随机点C组成的三角形的面积为

operator uInt()

请注意,鼠标的x位置不会影响三角形的区域

答案 1 :(得分:0)

根据您发现的数学公式,代码公式不应为:

let upTri = Math.abs((((this.xPos *(mousePos.y- farY )))+(mousePos.x *( farY -this.yPos ))+(farX *(this.yPos-mousePos.y)))/ 2);