javascript - 如何在 html Canvas 上找到三 Angular 形的面积?

标签 javascript html css html5-canvas

所以我画了一个矩形。

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

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

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

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

为了解决这个问题,我研究了鼠标坐标并从中减去。这产生了类似于我想要的结果,但我知道这不是我要确定的三 Angular 形的精确区域

如果有人对此有任何见解,那将不胜感激。 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>

最佳答案

水平线A、B与任意一点C所构成的三 Angular 形的面积为

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

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

关于javascript - 如何在 html Canvas 上找到三 Angular 形的面积?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59216434/

相关文章:

javascript - 翻译 Highcharts 中的事件

html - 任何简单的方法(也许使用CSS)可以根据书签突出显示网页的一部分(site.com/page.htm#bookmark

php - Wordpress- 一个使用短代码显示 HTML 内容(数据库)的插件

html - 打开我的网站时 Mac 上的鼠标滚轮问题

javascript - 如何让 hls.js 在请求加密 key 时在请求 header 中发送 cookie

javascript - 如何使用 angularjs 编辑输入值超出限制

css - 始终在父 div 的视口(viewport)中显示高度滚动条

css - 为什么动画 div 向上移动然后向右以跳跃结束?

html - 包含 float 元素的父元素没有背景

javascript - 设置下一个通知时间表LocalNotification Titanium Appcelerator