【手摸手带你实现可视化系统(一)】如何实现编辑面板的动态缩放?

382 阅读1分钟

「这是我参与2022首次更文挑战的第10天,活动详情查看:2022首次更文挑战

前言

最近在重构之前的一个可视化编辑项目,有点类似No-Code。在做中间主舞台的编辑时,因为要用户定义看板屏幕尺寸,所以需要在主舞台展示屏幕的缩放效果。

先看下最终的效果:

chrome-capture (4).gif

实现思路

  1. 首先需要将用户设定的屏幕尺寸:1920*1080的尺寸缩放到我们的主屏幕容器内,缩放可以使用css3的transtion: scale属性。
stageResize() {
  //外层容器的宽高
  const { width, height } =
    this.$refs.screen.parentNode.getBoundingClientRect();
  this.scale = Math.min(
    width / this.screen.width,
    height / this.screen.height
  );
  // console.log("width", width, this.scale);
},

先获取舞台外层容器的宽高,取外层容器宽高分别与用户设定屏幕尺寸取模的较小值,作为最终的缩放尺寸。这样可以保证不管用户设定怎样的长宽比,都能在舞台区域完美呈现。

  1. 防抖和resize 在组件挂载阶段监听resize事件,并触发舞台动态计算缩放比。记得在组件卸载或销毁阶段取消事件监听,防止内存泄漏的发生。
resizeDebounce: debounce(this.stageResize, 300),

mounted() {
    this.resizeDebounce();
    //   监听resize,缩放画布
    window.addEventListener("resize", this.resizeDebounce);
},
beforeDestroy() {
    window.removeEventListener("resize", this.resizeDebounce);
},

这里debounce是写在data里面的,也可以写在compouted里面,但是不能写在methods里面,作为一个函数返回,这样是不生效的。关于这个问题的前因后果,我准备单独开一篇文章具体讲下,有兴趣的同学可以持续关注下。

  1. 样式绑定
    screenConfig() {
      const {
        width,
        height,
        fontSize,
        whUnit = "",
        fontUnit = "",
      } = this.screen;
      return {
        // background: `linear-gradient(-90deg, ${this.gridColor} 1px, transparent 1px) 0% 0% / 20px 20px, linear-gradient(${this.gridColor} 1px, transparent 1px) 0% 0% / 20px 20px;`,
        ...this.screen,
        width: width + whUnit,
        height: height + whUnit,
        fontSize: fontSize + fontUnit,
        transform: `scale(${this.scale}) translate(-${
          ((1 / this.scale - 1) / 2) * 100
        }%, -${((1 / this.scale - 1) / 2) * 100}%)`,
        transition: "all 0.3s",
      };
    },

translate(-${ ((1 / this.scale - 1) / 2) * 100 }%, -${((1 / this.scale - 1) / 2) * 100}%),因为scale是以元素中心为缩放原点的,所以缩放之后需要将舞台移动到主区域的中心。假如scale = 0.2;说明缩放了5倍,我们就需要将舞台分别向上、向左移动2倍(200%)。

上面的效果得以实现,借鉴了阿里dateV的编辑页面的实现思路。

总结

以上就是编辑面板主舞台的动态缩放实现思路。

本篇文章也是从零实现可视化系统(仿阿里dataV) 的系列文章的第一篇,后续会持续分享在实现中遇到的难点和解决思路。

第二篇: 可视化系统开发之如何实现组件的自由变换?

写在最后

我是Back,一个热爱分享的前端开发者。如果觉得本文还不错,记得三连+关注,说不定哪天就用得上!您的鼓励是我坚持下去的最大动力❤️。