如何使用fabricjs计算画布边界内所有文本对象的面积?

6
我正在编写一个函数,用于计算画布上文本的总面积(使用其边界而不是文本本身),作为总画布大小的百分比。目前,它仅检查画布上所有文本对象的大小与画布的总面积,不考虑可能裁剪到画布边界外的文本的任何部分。
我想计算超出画布边界的总面积,并将其从文本对象的总面积中减去。
我的一些数学计算卡住了。执行此计算所需的基本信息如下:
- 画布的宽度和高度(px) - 文本对象的宽度和高度(px) - 对象的“left”和“bottom”位置(px)
首先,计算需要确定对象是否实际上超出了画布边界。然后,需要确定“left”或“bottom”位置是正还是负。
以下是我目前的代码,但我感觉我走错了方向:

  getTextCoverage() : number {
    var objects = this.canvas.getObjects();
    var canvasArea = this.canvasSize.width * this.canvasSize.height;
    var totalTextArea = 0;

// loop through all canvas objects
    for (var object of objects){
      if (object.text){
        // Check if the textbox is outside the canvas to the left or right
        var xOutsideCanvas = object.left + (object.width * object.scaleX) > object.width * object.scaleX ? 
          // If true the textbox is outside the canvas to the right
          this.canvas.width - (object.left + (object.width * object.scaleX)) : 
          // If false the textbox is outside the canvas to the left
          - this.canvas.width - (object.left + (object.width * object.scaleX));

        totalTextArea += (object.width * object.scaleX) * (object.height * object.scaleY);
        if(object.left + (object.width * object.scaleX) > this.canvas.width){
        }
      }
    }

    return ((totalTextArea / canvasArea) * 100) * 5;
  }

1个回答

7

我认为你的思路是正确的,我稍微修改了一下你的代码,使得它可以找到每个文本对象在画布上实际的最小和最大X/Y坐标。然后基于这些坐标就可以简单地计算出面积。噢,另外,在计算面积时不需要再次乘以缩放因子。

  if (object.text) {
    var minX = Math.max(0, object.left);
    var minY = Math.max(0, object.top);
    var right = (object.left + (object.width * object.scaleX));
    var maxX = Math.min(right, canvas.width);
    var bottom = (object.top + (object.height * object.scaleY));
    var maxY = Math.min(bottom, canvas.height);

    totalTextArea += ((maxX - minX) * (maxY - minY));
  }

传奇。这正是我想要的。谢谢! - Jeremy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接