【问题标题】:Canvas JS How to get height and width of polygon shape?Canvas JS 如何获取多边形的高度和宽度?
【发布时间】:2020-10-12 20:08:50
【问题描述】:

我创建了一个小画布 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();

但我无法获得其形状的宽度和高度,实际上我想显示和线条作为工具提示供用户参考。

我在这里附上图片,您可以在 Dice 顶部看到黑线(我在 Photoshop 中为您做参考)。我想展示那条线。 我是菜鸟,如果有人可以帮助我提供很棒的示例代码。

Example image

【问题讨论】:

    标签: javascript html5-canvas fabricjs


    【解决方案1】:

    您可以像这样获得最小/最大 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]);
    }
    

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

    【讨论】:

    • 非常感谢您的快速响应,但问题是坐标[0] 的位置并不总是最左或最右。它可以是顶部或中间形状。我相信我的要求并不容易,这是非常棘手的部分。例如,如果我有心形,我从顶部开始追踪它。
    • 这就是为什么您需要遍历所有点以找到最小和最大 x 和 y 值,正如我的回答所展示的那样
    • 我认为在幕后我们需要一些边界框,然后获取它的宽度和高度。
    • @Saba,你得到这里的边界框!
    • 你能帮一些jsfiddle的例子吗,通过这个循环我如何获得形状的宽度和高度?并在形状上画出那条线?我会非常感谢你
    猜你喜欢
    • 1970-01-01
    • 2015-08-15
    • 1970-01-01
    • 2017-03-15
    • 1970-01-01
    • 2015-08-05
    • 1970-01-01
    • 1970-01-01
    • 2013-11-09
    相关资源
    最近更新 更多