【问题标题】:How can I find the area of the triangle on the html canvas?如何在 html 画布上找到三角形的区域?
【发布时间】:2020-03-31 15:23:41
【问题描述】:

所以我画了一个矩形。

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

我用谷歌搜索了三角形面积的公式,并检查了很多次,确信它是正确的。它只是不起作用。

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

当用户在正方形内部单击时,我会知道当三角形的面积在数值上小于正方形的面积时,我会正确处理。唯一的问题是它实际上要大得多,我不知道如何从这里开始。

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

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

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>

【问题讨论】:

    标签: javascript html css html5-canvas


    【解决方案1】:

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

    upTri = this.width * Math.abs(mousePos.y - this.yPos) * 0.5;
    

    注意鼠标的x位置不影响三角形的面积

    【讨论】:

      【解决方案2】:

      根据你找到的数学公式,代码公式不应该是:

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

      【讨论】:

      • 很遗憾,不,我使用正方形的顶部两个角,这样就不会影响 y 坐标。我在帖子中画了一个插图来说明这一点。我什至在阅读您的帖子后再次检查了公式。谢谢您的建议。我希望插图能让问题更清楚。
      猜你喜欢
      • 1970-01-01
      • 2016-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-04
      • 1970-01-01
      相关资源
      最近更新 更多