Javascript 画布JS如何获得多边形形状的高度和宽度?

Javascript 画布JS如何获得多边形形状的高度和宽度?,javascript,html5-canvas,fabricjs,Javascript,Html5 Canvas,Fabricjs,我创建了一个小的canvas js脚本,并在形状上绘制了轮廓。这里是脚本 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.line

我创建了一个小的canvas js脚本,并在形状上绘制了轮廓。这里是脚本

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();
context.beginPath();
moveTo(坐标[0].x,坐标[0].y);
for(让index=1;index
但我无法得到它的宽度和高度的形状,实际上我想显示和线作为工具提示供用户参考

在这里,我附加的图像,你们可以看到上面的骰子黑色线(我做了你们的参考在photoshop)。我想展示那条线。 我是noob,如果有人能帮我编写示例代码,那就太好了


您可以按如下方式获得最小/最大X和Y:

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]);
}
var minx=坐标[0]。x,maxx=坐标[0]。x,miny==坐标[0]。y,maxy==坐标[0]。y;
for(让index=1;indexmaxx)maxx=坐标[index.x]);
如果(坐标[index.ymaxy)maxy=坐标[index.y]);
}

您可以使用最小值和最大值计算高度和宽度。

我非常感谢您的快速响应,但问题是坐标[0]的位置并不总是最左或最右。它可以是顶部或中间形状。我相信我的要求不是那么简单,这是非常棘手的部分。例如,如果我有一个心形,我从上到中开始跟踪它。这就是为什么你需要迭代所有点来找到最小值和最大值x和y,正如我的答案所示。我认为在场景后面我们需要一些边界框,然后得到它的宽度和高度。@Saba,你在这里得到了边界框!你们能帮我举一个JSFIDLE的例子吗?通过这个循环,我可以得到形状的宽度和高度?在形状上画一条线?我将非常感谢你