# 鞋带公式计算canvas多边形图形面积

$$S=\frac{1}{2}\left|\sum_{i=1}^{n}\left(x_{i} y_{i+1}-x_{i+1} y_{i}\right)\right|=\frac{1}{2}\left|\sum_{i=1}^{n} x_{i}\left(y_{i+1}-y_{i-1}\right)\right|$$

#### 例子

$$S_\text{triangle}=\frac{1}{2}\left| x_{1}\left(y_{2}-y_{3}\right) + x_{2}\left(y_{3}-y_{1}\right) + x_{3}\left(y_{1}-y_{2}\right) \right|$$

\begin{align} S_\text{triangle} &= \frac{1}{2} \left| 0 \cdot \left(1-1\right) + 1 \cdot \left(1-6\right) + 4 \cdot \left(6-1\right) \right| \\ &= \frac{1}{2} \left| -5 + 4 \times 5 \right| \\ &= 7.5 \end{align}

#### 代码

 const shoelaceFormula = (vertices: Array<{ x: number; y: number }>) => {
const length = vertices.length;
let area: number;
area = vertices.reduce((sum, vertice, i, array) => {
const afterIndex = i + 1 >= length ? 0 : i + 1;
const bforeIndex = i - 1 < 0 ? length - 1 : i - 1;
return sum + vertice.x * (array[afterIndex].y - array[bforeIndex].y);
}, 0);
return Math.abs(area) / 2;
};

Shoelace formula - Wikipedia

【国际数学竞赛】任意多边形面积计算公式

651 声望
14 粉丝
0 条评论