前端使用 Konva 实现可视化设计器(4)

上一章做一个补充,就是实现通过上下左右按键移动所选节点。

继续求 Star ,希望大家多多一键三连,十分感谢大家的支持~

创作不易,Star 50 个,创作加速!

github源码

gitee源码

示例地址

通过按键移动节点

准备工作

给 SelectionTool 添加两个必要的方法:

ts 复制代码
  // 更新已选位置
  selectingNodesAreaMove(offset: Konva.Vector2d) {
    this.selectingNodesArea?.x(this.selectingNodesArea.x() + offset.x)
    this.selectingNodesArea?.y(this.selectingNodesArea.y() + offset.y)
  }

  // 更新节点位置
  selectingNodesMove(offset: Konva.Vector2d) {
    for (const node of this.render.selectionTool.selectingNodes) {
      node.x(node.x() + offset.x)
      node.y(node.y() + offset.y)
    }
  }

根据上一章的设计,选中一个/多个节点的时候,还会伴随一个 group 作为辅助,所以我们除了移动所选节点的同时,还需要移动 selectingNodesArea。

按键控制,就是需要处理 dom 的 keydown 和 keyup 两个事件,放在 KeyMoveHandlers 文件中,这里是核心代码:

ts 复制代码
      keydown: (e: GlobalEventHandlersEventMap['keydown']) => {
        if (!e.ctrlKey) {
          if (
            Object.values(Types.MoveKey)
              .map((o) => o.toString())
              .includes(e.code)
          ) {
            if (e.code === Types.MoveKey.上) {
              this.render.selectionTool.selectingNodesAreaMove({ x: 0, y: -this.speed })
              this.render.selectionTool.selectingNodesMove({ x: 0, y: -this.speed })
            } else if (e.code === Types.MoveKey.左) {
              this.render.selectionTool.selectingNodesAreaMove({ x: -this.speed, y: 0 })
              this.render.selectionTool.selectingNodesMove({ x: -this.speed, y: 0 })
            } else if (e.code === Types.MoveKey.右) {
              this.render.selectionTool.selectingNodesAreaMove({ x: this.speed, y: 0 })
              this.render.selectionTool.selectingNodesMove({ x: this.speed, y: 0 })
            } else if (e.code === Types.MoveKey.下) {
              this.render.selectionTool.selectingNodesAreaMove({ x: 0, y: this.speed })
              this.render.selectionTool.selectingNodesMove({ x: 0, y: this.speed })
            }

            if (this.speed < this.speedMax) {
              this.speed++
            }
          }
        }
      },
      keyup: () => {
        this.speed = 1
      }

这里设计的规则是,按一下移动 1 像素,按着不动则会按 1 像素增速移动,松开按键则恢复原来速度。

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

  • 放大缩小所选的"磁贴效果"(基于网格)
  • 拖动所选的"磁贴效果"(基于网格)
  • 节点层次单个、批量调整
  • 键盘复制、粘贴
  • 等等。。。

是不是更加有趣呢?是不是值得更多的 Star 呢?勾勾手指~

源码

gitee源码

示例地址

相关推荐
sbjdhjd7 小时前
Redis 主从复制、哨兵高可用与 Cluster 集群部署实验手册
运维·前端·redis·云原生·开源·bootstrap·html
乐兮创想 小林7 小时前
企业官网移动端性能优化实战:从 Core Web Vitals 到图片/CDN/响应式的工程清单
前端·性能优化·网站建设·北京网站建设公司
前端一小卒8 小时前
不手写代码的第 30 天,我才明白前端这个岗位还剩什么
前端·javascript·ai编程
Ajie'Blog8 小时前
Copilot Agent Tasks API 开放:AI 编程开始进入后台任务时代
服务器·前端·javascript·人工智能·copilot·ai编程
老毛肚8 小时前
jeecgboot vue TS & 模板化 04
前端·javascript·vue.js
AI_零食10 小时前
鸿蒙PC Electron跨平台应用开发:24时区时间表应用详解
前端·华为·electron·开源·harmonyos·鸿蒙
Electrolux10 小时前
[onlyoffice-v9]纯前端怎么实现编辑预览office
前端·javascript·github
码云之上10 小时前
聊聊如何设计一个高效、稳定的 Node.js 接入层
前端·后端·node.js
kyriewen11 小时前
我读了一遍 Babel 编译后的 async/await,终于搞懂了它的原理(附 20 行手写实现)
前端·javascript·面试
IT_陈寒11 小时前
Vite项目build后路由404了?你可能漏了这个小配置
前端·人工智能·后端