首页 > 其他分享 >前端使用 Konva 实现可视化设计器(10)- 对齐线

前端使用 Konva 实现可视化设计器(10)- 对齐线

时间:2024-05-11 22:43:39浏览次数:15  
标签:node 10 const render Konva value 对齐 id

请大家动动小手,给我一个免费的 Star 吧~

大家如果发现了 Bug,欢迎来提 Issue 哟~

github源码

gitee源码

示例地址

不知不觉来到第 10 章了,感觉接近尾声了。。。

对齐线

先看效果:
image

这里交互有两个部分:
1、节点之间的对齐线
2、对齐磁贴

多选的情况下,效果是一样的:
image

主要逻辑会放在控制“选择”的代码文件里:
src\Render\handlers\SelectionHandlers.ts
这里需要一些辅助都定义:

interface SortItem {
  id?: number // 有 id 就是其他节点,否则就是 选择目标
  value: number // 左、垂直中、右的 x 坐标值; 上、水平中、下的 y 坐标值;
}

type SortItemPair = [SortItem, SortItem]

尝试画个图说明一下上面的含义:

这里以纵向(基于 x 坐标值)为例:

image
这里的 x1~x9,就是 SortItem,横向(基于 y 坐标值)同理,特别地,如果是正在拖动的目标节点,会把该节点的 _id 记录在 SortItem 以示区分。

会存在一个处理,把一个方向上的所有 x 坐标进行从小到大的排序,然后一双一双的遍历,需要符合以下条件“必须分别属于相邻的两个节点”的 SortItem 对,也就是 SortItemPair。

在查找所有 SortItemPair 的同时,只会更新并记录节点距离最短的那些 SortItemPair(可能会存在多个)。

核心逻辑代码:

  // 磁吸逻辑
  attract = (newPos: Konva.Vector2d) => {
    // 对齐线清除
    this.alignLinesClear()

    // stage 状态
    const stageState = this.render.getStageState()

    const width = this.render.transformer.width()
    const height = this.render.transformer.height()

    let newPosX = newPos.x
    let newPosY = newPos.y

    let isAttract = false

    let pairX: SortItemPair | null = null
    let pairY: SortItemPair | null = null

    // 对齐线 磁吸逻辑
    if (this.render.config.attractNode) {
      // 横向所有需要判断对齐的 x 坐标
      const sortX: Array<SortItem> = []
      // 纵向向所有需要判断对齐的 y 坐标
      const sortY: Array<SortItem> = []

      // 选择目标所有的对齐 x
      sortX.push(
        {
          value: this.render.toStageValue(newPos.x - stageState.x) // 左
        },
        {
          value: this.render.toStageValue(newPos.x - stageState.x + width / 2) // 垂直中
        },
        {
          value: this.render.toStageValue(newPos.x - stageState.x + width) // 右
        }
      )

      // 选择目标所有的对齐 y
      sortY.push(
        {
          value: this.render.toStageValue(newPos.y - stageState.y) // 上
        },
        {
          value: this.render.toStageValue(newPos.y - stageState.y + height / 2) // 水平中
        },
        {
          value: this.render.toStageValue(newPos.y - stageState.y + height) // 下
        }
      )

      // 拖动目标
      const targetIds = this.render.selectionTool.selectingNodes.map((o) => o._id)
      // 除拖动目标的其他
      const otherNodes = this.render.layer.getChildren((node) => !targetIds.includes(node._id))

      // 其他节点所有的 x / y 坐标
      for (const node of otherNodes) {
        // x
        sortX.push(
          {
            id: node._id,
            value: node.x() // 左
          },
          {
            id: node._id,
            value: node.x() + node.width() / 2 // 垂直中
          },
          {
            id: node._id,
            value: node.x() + node.width() // 右
          }
        )
        // y
        sortY.push(
          {
            id: node._id,
            value: node.y() // 上
          },
          {
            id: node._id,
            value: node.y() + node.height() / 2 // 水平中
          },
          {
            id: node._id,
            value: node.y() + node.height() // 下
          }
        )
      }

      // 排序
      sortX.sort((a, b) => a.value - b.value)
      sortY.sort((a, b) => a.value - b.value)

      // x 最短距离
      let XMin = Infinity
      // x 最短距离的【对】(多个)
      let pairXMin: Array<SortItemPair> = []

      // y 最短距离
      let YMin = Infinity
      // y 最短距离的【对】(多个)
      let pairYMin: Array<SortItemPair> = []

      // 一对对比较距离,记录最短距离的【对】
      // 必须是 选择目标 与 其他节点 成【对】
      // 可能有多个这样的【对】

      for (let i = 0; i < sortX.length - 1; i++) {
        // 相邻两个点,必须为 目标节点 + 非目标节点
        if (
          (sortX[i].id === void 0 && sortX[i + 1].id !== void 0) ||
          (sortX[i].id !== void 0 && sortX[i + 1].id === void 0)
        ) {
          // 相邻两个点的 x 距离
          const offset = Math.abs(sortX[i].value - sortX[i + 1].value)
          if (offset < XMin) {
            // 更新 x 最短距离 记录
            XMin = offset
            // 更新 x 最短距离的【对】 记录
            pairXMin = [[sortX[i], sortX[i + 1]]]
          } else if (offset === XMin) {
            // 存在多个 x 最短距离
            pairXMin.push([sortX[i], sortX[i + 1]])
          }
        }
      }

      for (let i = 0; i < sortY.length - 1; i++) {
        // 相邻两个点,必须为 目标节点 + 非目标节点
        if (
          (sortY[i].id === void 0 && sortY[i + 1].id !== void 0) ||
          (sortY[i].id !== void 0 && sortY[i + 1].id === void 0)
        ) {
          // 相邻两个点的 y 距离
          const offset = Math.abs(sortY[i].value - sortY[i + 1].value)
          if (offset < YMin) {
            // 更新 y 最短距离 记录
            YMin = offset
            // 更新 y 最短距离的【对】 记录
            pairYMin = [[sortY[i], sortY[i + 1]]]
          } else if (offset === YMin) {
            // 存在多个 y 最短距离
            pairYMin.push([sortY[i], sortY[i + 1]])
          }
        }
      }

      // 取第一【对】,用于判断距离是否在阈值内

      if (pairXMin[0]) {
        if (Math.abs(pairXMin[0][0].value - pairXMin[0][1].value) < this.render.bgSize / 2) {
          pairX = pairXMin[0]
        }
      }

      if (pairYMin[0]) {
        if (Math.abs(pairYMin[0][0].value - pairYMin[0][1].value) < this.render.bgSize / 2) {
          pairY = pairYMin[0]
        }
      }

      // 优先对齐节点

      // 存在 1或多个 x 最短距离 满足阈值
      if (pairX?.length === 2) {
        for (const pair of pairXMin) {
          // 【对】里的那个非目标节点
          const other = pair.find((o) => o.id !== void 0)
          if (other) {
            // x 对齐线
            const line = new Konva.Line({
              points: _.flatten([
                [other.value, this.render.toStageValue(-stageState.y)],
                [other.value, this.render.toStageValue(this.render.stage.height() - stageState.y)]
              ]),
              stroke: 'blue',
              strokeWidth: this.render.toStageValue(1),
              dash: [4, 4],
              listening: false
            })
            this.alignLines.push(line)
            this.render.layerCover.add(line)
          }
        }
        // 磁贴第一个【对】
        const target = pairX.find((o) => o.id === void 0)
        const other = pairX.find((o) => o.id !== void 0)
        if (target && other) {
          // 磁铁坐标值
          newPosX = newPosX - this.render.toBoardValue(target.value - other.value)
          isAttract = true
        }
      }

      // 存在 1或多个 y 最短距离 满足阈值
      if (pairY?.length === 2) {
        for (const pair of pairYMin) {
          // 【对】里的那个非目标节点
          const other = pair.find((o) => o.id !== void 0)
          if (other) {
            // y 对齐线
            const line = new Konva.Line({
              points: _.flatten([
                [this.render.toStageValue(-stageState.x), other.value],
                [this.render.toStageValue(this.render.stage.width() - stageState.x), other.value]
              ]),
              stroke: 'blue',
              strokeWidth: this.render.toStageValue(1),
              dash: [4, 4],
              listening: false
            })
            this.alignLines.push(line)
            this.render.layerCover.add(line)
          }
        }
        // 磁贴第一个【对】
        const target = pairY.find((o) => o.id === void 0)
        const other = pairY.find((o) => o.id !== void 0)
        if (target && other) {
          // 磁铁坐标值
          newPosY = newPosY - this.render.toBoardValue(target.value - other.value)
          isAttract = true
        }
      }
    }

虽然代码比较冗长,不过逻辑相对还是比较清晰,找到满足条件(小于阈值,足够近,这里阈值为背景网格的一半大小)的 SortItemPair,就可以根据记录的坐标值大小,定义并绘制相应的线条(添加到 layerCover 中),记录在某个变量中:

  // 对齐线
  alignLines: Konva.Line[] = []

  // 对齐线清除
  alignLinesClear() {
    for (const line of this.alignLines) {
      line.remove()
    }
    this.alignLines = []
  }

在适合的时候,执行 alignLinesClear 清空失效的对齐线即可。

接下来,计划实现下面这些功能:

  • 连接线
  • 等等。。。

More Stars please!勾勾手指~

源码

gitee源码

示例地址

标签:node,10,const,render,Konva,value,对齐,id
From: https://www.cnblogs.com/xachary/p/18187292

相关文章

  • 敏捷冲刺-5月10日
    敏捷冲刺-Day-05所属课程软件工程2024作业要求团队作业4—项目冲刺作业目标完成第5篇Scrum冲刺博客冲刺日志集合贴https://www.cnblogs.com/YXCS-cya/p/181788031.项目燃尽图1.1第五日-5月10日进度当前进度逐渐加快2.会议记录2.1会议主题第5......
  • 关于VHDL中Loop State error...loop must terminate within 10,000 iterations错误解
    关于VHDL中LoopStateerror...loopmustterminatewithin10,000iterations错误解决方法首先比较下面两段代码:(使用while循环描述偶校验位产生电路)代码一:libraryieee;useieee.std_logic_1164.all;useieee.std_logic_unsigned.all;useieee.std_logic_arith.all;ent......
  • 专业商用远程控制软件,低至10元每月
    如今不论工作还是生活,远程控制软件已成为我们的必备工具。说到远程软件,市面上有很多款。但“个人免费版”,往往会有限速、卡顿、不清晰等问题;商业版很强大,但普遍价格昂贵。那么有没有既便宜又专业的商业级远控软件呢?现在,它来了,它来了!Splashtop家族的商业版远程软件BusinessAcc......
  • 5.10洛谷收获
    1.求幂函数#includepow(a,b);计算a的b次幂2.error:invalidtypes'int[int]'forarraysubscript|记住这个错误吧,犯过好多次了数组变量名不一致或者是没定义数组空间不够变量名和数组名重复定义3.快速幂快速幂本质上是一个倍增问题,比如说要求6的34次方如果34个6相乘......
  • MSB410在条件(%(Name)' == InputFile' OR %(Name)' == OutputFile
    问题:在VS2017中配置完了Qtvisualstudiotools插件后,编译时报错< MSB410在条件(%(Name)'==InputFile'OR%(Name)'==OutputFile > 原因及解决方法:插件版本问题,先卸载最新版,下载旧版:https://download.qt.io/archive/vsaddin/  此版本报错 安装后断网,取消自动更......
  • GBU810-ASEMI开关电源整流桥GBU810
    编辑:llGBU810-ASEMI开关电源整流桥GBU810型号:GBU810品牌:ASEMI封装:GBU-4正向电流(Id):8A反向耐压(VRRM):1000V正向浪涌电流:200A正向电压(VF):1.10V引脚数量:4芯片个数:4芯片尺寸:88MIL功率(Pd):中小功率设备工作温度:-55°C~150°C类型:整流桥、插件整流桥GBU810整流桥描述:ASEMI品......
  • AIX7100-安装JDK1.8
    上传java8_64.zip解压java8_64.zip链接:https://pan.baidu.com/s/1ALnhiXLkDWbbhyfCf8djVQ?pwd=hz28提取码:hz28#cd/usr/local/#unzipjava8_64.zip#vi/etc/profile#find/usr/local/java8_64-name"java"-typef/usr/local/java8_64/jre/bin/java"......
  • 在win10右下角显示时间秒
    1、首先按组合键“win+r”打开运行窗口,在窗口中输入regedit,按回车键进入注册表编辑器或者按组合键“win+x”在PowerShell中执行命令regedit(效果相同)进入注册表编辑器之后依次找到:HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersio\Explorer\Advanced,新建DWORD(32......
  • 2024 年 5 月 10 日 周五 阴 凉(1025 字)
    正文上午真的好困。反正这两天处于交接工作的状态,我在二楼或者一楼都行,没人管我。于是我就跑到三楼,躺在了自己的床上(笑。本想稍微睡一下就好了,毕竟还在工作时间,从9:48-10:10。结果太困了,多睡了会儿,到10:32。下去似乎还是没人管。精神确实好了一些。起码做事不会感到一股强......
  • KBU1010-ASEMI新能源专用KBU1010
    编辑:llKBU1010-ASEMI新能源专用KBU1010型号:KBU1010品牌:ASEMI封装:KBU-4最大重复峰值反向电压:1000V最大正向平均整流电流(Vdss):10A功率(Pd):中小功率芯片个数:4引脚数量:4类型:插件整流桥、整流扁桥正向浪涌电流:300A正向电压:1.10V最大输出电压(RMS):封装尺寸:如图工作温度:-55......