获取多边形的面积

时间:2018-11-20 01:01:29

标签: javascript math

我试图在画布元素中获取多边形绘制onclick的区域

enter image description here

在上面的图片中,我尝试获取红色点内具有一定透明度的区域。

无论如何,“即时”执行此操作意味着每次多边形绘制。

我已经看到了允许进行三角剖分的earcut.js,但我真的不明白如何通过该区域来获取

var canvas = $('canvas');
var context = canvas[0].getContext('2d');
var imageObj = new Image(); 
  
imageObj.onload = function() {
  $(canvas).attr({
    width : this.width,
    height: this.height
  });
  context.drawImage(imageObj,0,0); 
}; 
imageObj.src = 'https://www.html5canvastutorials.com/demos/assets/darth-vader.jpg'; 

var clicks = [];


function drawPolygon(){
  context.fillStyle = 'rgba(100,100,100,0.5)';
  context.strokeStyle = "#df4b26";
  context.lineWidth = 1;
  
  context.beginPath();
  context.moveTo(clicks[0].x, clicks[0].y);
  for(var i=1; i < clicks.length; i++) { 
    context.lineTo(clicks[i].x,clicks[i].y);

  }
  context.closePath();
  context.fill();
  context.stroke();
};

function drawPoints(){
  context.strokeStyle = "#df4b26"; 
  context.lineJoin = "round"; 
  context.lineWidth = 5; 
              
  for(var i=0; i < clicks.length; i++){ 
    context.beginPath(); 
    context.arc(clicks[i].x, clicks[i].y, 3, 0, 2 * Math.PI, false); 
    context.fillStyle = '#ffffff'; 
    context.fill(); 
    context.lineWidth = 5; 
    context.stroke(); 
  }
};
  
function redraw(){ 
  canvas.width = canvas.width; // Clears the canvas 
  context.drawImage(imageObj,0,0); 
    
  drawPolygon();
  drawPoints();
};

canvas
  .mouseup(function (e) {
    clicks.push({
      x: e.offsetX,
      y: e.offsetY
    });
    redraw(); 
 });
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>draw polygon with canvas</title>
  
  
  
      <link rel="stylesheet" href="css/style.css">

  
</head>

<body>

  <canvas	width="600" height="400"></canvas>
  <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>

  

    <script  src="js/index.js"></script>




</body>

</html>

1 个答案:

答案 0 :(得分:2)

有一种非常简单的算法来计算具有给定顶点坐标Shoelace formula

的多边形的面积
A = 1/2* Sum((x[i+1] + x[i]) * ([y[i+1] - y[i]))

 (note indexes wrap in circular manner, so x[n]=x[0])

可以在单个循环中实现。