我正在尝试计算给出一些可以为负的坐标的多边形的面积。 当我仅传递负坐标时,它会给我一个负区域;当我传递仅正值时,它会给我一个正数;但是当我给它一个混合值时,[[-1,0],[-1,1],[1,1] ,[1,0])总是给我负面的印象。
我的代码是:
function calculateArea(coords) {
area = 0;
points = coords.length;
j = points - 1;
for (i = 0; i < points; i++) {
area += (coords[i][0] + coords[j][0]) * (coords[i][1] - coords[j][1])
j = i;
}
return area / 2;
}
coords是[x,y]坐标的数组。
问题是,我不确定,但是我认为如果我返回计算出的面积的绝对值,那应该是正确的。 我是否缺少某些东西或返回绝对值应该没问题?
答案 0 :(得分:1)
区域符号取决于您对顶点的排序方式,而不取决于某些坐标是否为负。
假设公式本身正确,则可以简单地使用Math.abs
始终获得正值。
function calculateArea(coords) {
let area = 0;
for (let i = 0; i < coords.length; i++) {
const [x1, y1] = coords[i];
const [x2, y2] = coords[(i + 1) % coords.length];
area += x1 * y2 - x2 * y1
}
return area / 2;
// replace with
// return Math.abs(area) / 2;
}
console.log('Clockwise:', calculateArea([
[-1, 0],
[-1, 1],
[1, 1],
[1, 0]
]))
console.log('Counterclockwise:', calculateArea([
[-1, 0],
[-1, 1],
[1, 1],
[1, 0]
].reverse()))