Skip to content

Instantly share code, notes, and snippets.

@JordanDelcros
Created July 30, 2015 08:48
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JordanDelcros/cea7b8b231660ebccc6f to your computer and use it in GitHub Desktop.
Save JordanDelcros/cea7b8b231660ebccc6f to your computer and use it in GitHub Desktop.
Find centroid of a triangle with JavaScript
// Very simple way to compute the center (centroid) of a triangle.
// The only things you have to know are the three vectors forming the triangle.
// vector = [x, y, z];
var vectorA = [-1, -3, -2];
var vectorB = [2, 1, 2];
var vectorC = [8, -4, 1];
var centerX = ((vectorA[0] + vectorB[0] + vectorC[0]) / 3);
var centerY = ((vectorA[1] + vectorB[1] + vectorC[1]) / 3);
var centerZ = ((vectorA[2] + vectorB[2] + vectorC[2]) / 3);
var center = [centerX, centerY, centerZ];
@Vamoss
Copy link

Vamoss commented May 23, 2020

2D function:

function getTriangleCentroid(arr){
	var centerX = (arr[0].x + arr[1].x + arr[2].x) / 3;
	var centerY = (arr[0].y + arr[1].y + arr[2].y) / 3;
	return createVector(centerX, centerY);
}

Usage:

console.log(getTriangleCentroid([{x: -1, y: 2}, {x: -3, y: 1}, {x: -2, y: 2}]));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment