【问题标题】:Fabric JS - How to check if an object collides with another object on its Y-axis(Vertically)Fabric JS - 如何检查一个对象是否在其 Y 轴上与另一个对象碰撞(垂直)
【发布时间】:2020-06-17 18:51:27
【问题描述】:

我试图在画布上保持不同大小的图像对象之间的最小垂直间隙。 我无法弄清楚如何与最近的垂直物体保持最小间隙(如果有的话)。如果我能以某种方式让对象垂直(Y 轴)与当前放置的对象发生碰撞,我认为这足以保持间隙。

【问题讨论】:

    标签: javascript typescript html5-canvas fabricjs


    【解决方案1】:

    我通过迭代画布的每个对象并获取并检查迭代对象的边界矩形 top+height 是否大于或等于对象的边界矩形 top 需要放置。这是代码示例

    const presentObjs = canvas.getObjects();
    let objectToBeplaced = presentObjs[3]; //random object just for example, please change according to your need.
    let currentObj = objectToBePlaced;
    const presentObjsCount = presentObjs.length;
    const gapY = 10;//10 points gap vertically
    let j;
    for (j = 0; j < presentObjsCount; j++)
    {
                const obj = presentObjs[j];
                if (obj === currentObj) {
                  continue;
                }
                const objBox = obj.getBoundingRect();
                const objW = Math.ceil(Math.abs(objBox.width));
                const objLeft = Math.ceil(Math.abs(objBox.left));
                const objH = Math.ceil(Math.abs(objBox.height));
                const objTop = Math.ceil(Math.abs(objBox.top));
    
                const cObjBox = currentObj.getBoundingRect();
                const cObjW = Math.ceil(Math.abs(cObjBox.width));
                const cObjLeft = Math.ceil(Math.abs(cObjBox.left));
                const cObjH = Math.ceil(Math.abs(cObjBox.height));
                const cObjTop = Math.ceil(Math.abs(cObjBox.top));
    
                const a = cObjLeft;
                const b = cObjLeft + cObjW;
                const x = objLeft;
                const y = objLeft + objW;
    
                    if ((x >= a && x <= b) || (y >= a && y <= b) || (a >= x && b <= x) || (a >= y && b <= y)) { //Checks if both object has intersection on Y-axis
                  if ((cObjTop - (objTop + objH)) < gapY && (cObjTop - (objTop + objH)) >= 0) { //checks  if gap is less than needed
                    currentObj.set({ top: objTop + objH + gapY });
                    currentObj.setCoords();
                  }
                }
    }
    canvas.renderAll();
    

    如有任何问题或疑问,请随时提出。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多