You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用PowerPoint JS API(2024年3月最新版)连接两个矩形?

PowerPoint JS API 实现形状的官方连接线绑定

要实现微软官方定义的“形状连接线”(移动形状时线条自动跟随调整),核心是给创建的连接线绑定目标形状的连接点,而非手动设置线条坐标。以下是修正后的代码及关键说明:

修正后的完整代码

export async function run() {
  await PowerPoint.run(async (context) => {
    const shapes = context.presentation.slides.getItemAt(0).shapes;

    // 创建矩形1
    const rectangle1 = shapes.addGeometricShape(PowerPoint.GeometricShapeType.rectangle);
    rectangle1.left = 100;
    rectangle1.top = 50;
    rectangle1.height = 150;
    rectangle1.width = 50;
    rectangle1.name = "Rectangle1";

    // 创建矩形2
    const rectangle2 = shapes.addGeometricShape(PowerPoint.GeometricShapeType.rectangle);
    rectangle2.left = 300;
    rectangle2.top = 50;
    rectangle2.height = 150;
    rectangle2.width = 100;
    rectangle2.name = "Rectangle2";

    // 创建连接线(指定为straight类型的连接器)
    const line = shapes.addLine(PowerPoint.ConnectorType.straight);
    line.name = "StraightLine";

    // 绑定连接线到两个矩形的连接点
    // rectangle1的右侧中间连接点(索引3)
    line.beginConnectedShape = rectangle1;
    line.beginConnectionSiteIndex = 3;
    // rectangle2的左侧中间连接点(索引1)
    line.endConnectedShape = rectangle2;
    line.endConnectionSiteIndex = 1;

    await context.sync();
  });
}

关键说明

  1. 连接点索引规则:标准矩形的连接点索引为:
    • 1:左侧中间
    • 2:顶部中间
    • 3:右侧中间
    • 4:底部中间
      其他形状的连接点总数可通过shape.connectionSiteCount查看,再按需选择对应索引。
  2. 无需手动设置线条位置:绑定连接点后,PowerPoint会自动计算并调整连接线的位置、长度,移动矩形时线条会自动跟随变化,无需手动设置left/top/width/height。
  3. 官方资料位置:微软Office JS官方文档的PowerPoint Shape接口章节,搜索beginConnectedShape、endConnectedShape或ConnectorType即可找到2024年的最新说明。

内容的提问来源于stack exchange,提问作者user715022

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 23:53:28