Hi @peterson,
In p5.js, the area of a triangle can be computed using the following formula:
abs(x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0
Below is p5.js code for drawing a triangle and computing its area. Since the coordinates of the vertices relate to pixels, the computed area is in square pixel units.
/*
Computes area of triangle based on coordinates of vertices
abs(x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0
*/
function setup() {
createCanvas(400, 400);
background(255, 255, 128);
noLoop();
textAlign(CENTER, CENTER);
}
function draw() {
// vertices of triangle are (40, 36), (80, 360), and (320, 180)
let x1 = 40;
let y1 = 36;
let x2 = 80;
let y2 = 360;
let x3 = 320;
let y3 = 180;
// draw triangle with gray stroke and white fill
stroke(128);
fill(255);
triangle(x1, y1, x2, y2, x3, y3);
label_vertex(x1, y1);
label_vertex(x2, y2);
label_vertex(x3, y3);
label_area(x1, y1, x2, y2, x3, y3);
}
function area_of_triangle(x1, y1, x2, y2, x3, y3) {
// compute area in pixel units
return abs(x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0;
}
function label_vertex(x, y) {
textSize(20);
// make the text blue
fill(0, 0, 255);
text("("+ x + ", " + y + ")", x, y);
}
function label_area(x1, y1, x2, y2, x3, y3) {
textSize(20);
// make the text blue
fill(0, 0, 255);
// get area
let area = area_of_triangle(x1, y1, x2, y2, x3, y3);
// place label of area in center of triangle
text("Area: " + area, (x1 + x2 + x3) / 3, (y1 + y2 + y3) / 3);
}
This is the image produced by the code:
Please feel free to ask if you have any questions at all about the code.