javascripthtml5-canvasfabricjs

Canvas JS How to get height and width of polygon shape?


I created a small canvas js script and draw outline on shape here is the script

context.beginPath();
context.moveTo(coordinates[0].x, coordinates[0].y);
for (let index = 1; index < coordinates.length; index++) {
    context.lineTo(coordinates[index].x, coordinates[index].y);
}
context.lineWidth = 2;
context.strokeStyle = "red";
context.fillStyle = "rgba(255, 0, 0, 0.3)";
context.fill()
context.closePath();
context.stroke();

But i am unable to get its width and height of shape, actually i want to display and line as tooltip for user reference.

Here i attach image you can see black line on top of Dice (i did for your reference in photoshop). i want to show that line. i am noob, if any one can help me with example code that would be great.

Example image


Solution

  • You can get the min/max X and Y like this:

    var minx = coordinates[0].x, maxx = coordinates[0].x, miny = coordinates[0].y, maxy = coordinates[0].y;
    for (let index = 1; index < coordinates.length; index++) {
      if (coordinates[index].x < minx) minx = coordinates[index.x];
      if (coordinates[index].x > maxx) maxx = coordinates[index.x];
      if (coordinates[index].y < miny) miny = coordinates[index.y];
      if (coordinates[index].y > maxy) maxy = coordinates[index.y];
    }
    

    You can calculate height and width using the min and max values.