菜鸟笔记002 目标对象的中心点与源对象的中心点对齐,获取对象中心坐标

上层对象设置为: 源对象

下层对象设置为: 目标对象

代码如下:(目前不支持蒙版对象)

// 获取当前活动的文档
var doc = app.activeDocument;

// 确保有至少两个选定对象
if (doc.selection.length >= 2) {
    // 获取第一个选定对象(源对象)
    var sourceItem = doc.selection[0];
    // 获取第二个选定对象(目标对象)
    var targetItem = doc.selection[1];

    // 获取源对象的边界矩形(bounding box)
    var sourceBounds = sourceItem.geometricBounds;
    
    // 计算源对象的中心点 X 和 Y 值
    var sourceCenterX = (sourceBounds[0] + sourceBounds[2]) / 2;
    var sourceCenterY = (sourceBounds[1] + sourceBounds[3]) / 2;
    
    // 获取目标对象的边界矩形(bounding box)
    var targetBounds = targetItem.geometricBounds;
    
    // 计算目标对象的宽度和高度
    var targetWidth = targetBounds[2] - targetBounds[0];
    var targetHeight = targetBounds[3] - targetBounds[1];
    
    // 计算目标对象的中心点 X 和 Y 值
    var targetCenterX = (targetBounds[0] + targetBounds[2]) / 2;
    var targetCenterY = (targetBounds[1] + targetBounds[3]) / 2;
    
    // 计算目标对象的新位置(使目标对象的中心点与源对象的中心点对齐)
    var deltaX = sourceCenterX - targetCenterX;
    var deltaY = sourceCenterY - targetCenterY;
    
    // 移动目标对象
    targetItem.left += deltaX;
    targetItem.top += deltaY;

    // 输出新的目标对象位置
    alert("目标对象的位置已调整,中心点 X 和 Y 值已与源对象对齐。");
} else {
    alert("请选定两个对象。");
}