skip to Main Content

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

2

Answers


  1. 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.

    Login or Signup to reply.
  2. If your polygon looks like following, this could be the fastest solution.

    var polygon = [1678, 385, 1726, 388, 1725, 427, 1679, 427];
    
    var minX = Math.min(...polygon.filter((_, i) => i % 2 === 0));
    var maxX = Math.max(...polygon.filter((_, i) => i % 2 === 0));
    var minY = Math.min(...polygon.filter((_, i) => i % 2 === 1));
    var maxY = Math.max(...polygon.filter((_, i) => i % 2 === 1));
    
    var width = maxX - minX;
    var height = maxY - minY;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search