3

I am giving the user the ability to click from point to point however they want. My goal is to calculate the area of whatever they created. The problem is that it isn't always going to be a perfect square or triangle, etc.. It seems like all I have to work with is logging the changes in the coordinates each time they click and doing a manual calculation. Is there an easy way to get the filled in area of a Path2D() or is it very complicated?

enter image description here

Here is my current code:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
// ctx.moveTo(0, 0);
// ctx.lineTo(200, 100);
// ctx.stroke();

const path = new Path2D();

c.addEventListener('mousedown', function(e) {
    const x = event.clientX - rect.left;
    const y = event.clientY - rect.top;


    ctx.strokeStyle = "black";
    ctx.lineWidth = 5;

    path.lineTo(x, y);
    ctx.stroke(path);
    ctx.fill(path);

    console.log(path);

    // console.log(x);
    // console.log(y);

    // ctx.lineTo(x, y);
    // ctx.stroke();
    // ctx.fillStyle = "red";
    // ctx.fill();
});
Blake Rivell
  • 13,105
  • 31
  • 115
  • 231
  • Why not store the points of the paths and then use any polygon area formula? – kelsny May 23 '22 at 16:12
  • @catgirlkelly This sounds really good, not sure why I didn't think of this. Can you provide a simple example? – Blake Rivell May 23 '22 at 16:23
  • Hm well there are some solutions described [here](https://stackoverflow.com/questions/16285134/calculating-polygon-area), but I just played around with your code and I see that the `fill` method does some quite... janky unexpected things. The computed area might not match what you see on screen. – kelsny May 23 '22 at 16:25
  • Just searching "area arbitrary polygon" gave me [shoelace formula](https://en.wikipedia.org/wiki/Shoelace_formula) that also describes the trapezoid formula which, despite all the math, seems pretty easy to implement. – Ouroborus May 23 '22 at 20:02

0 Answers0