我正在尝试在画布上不同尺寸的图像对象之间保持最小的垂直间隙。我无法弄清楚如何用最接近的垂直物体保持最小间隙。如果我能以某种方式使对象垂直(Y轴)与当前放置的对象碰撞,我认为足以保持间隙。
我通过遍历画布的每个对象并获取并检查迭代对象的边界矩形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();
随时询问是否有疑问。