大屏兼容之scale方案

1,375 阅读2分钟

常见方案

  • vh、vw方案:将所有的尺寸根据设计图换算成vw和vh
  • scale方案:根据设计图的尺寸和当前屏幕的尺寸计算缩放的比例
  • rem方案:根据设计图和屏幕尺寸计算根元素font-size,其他尺寸通过插件换算成rem

scale兼容的优缺点

优点:1、代码量极少,只需要处理一次container;2、其他各种图表不用单独进行适配
缺点:1、因为是根据ui进行等比例缩放,所以左右和上下可能会出现白边;2、放大倍数过大会导致图片等失真变模糊(可以让ui出8倍的图 然后整体也按照正常分辨率的8倍去编写,这样可以去极大的避免这种情况,缺点就是图片会变得很大,造成图片加载慢);3、缩放之后高德地图,百度地图、echarts等的事件热区会偏移。

代码示例

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        padding: 0;
        margin: 0;
      }
      .demo1 {
        width: 1920px;
        height: 1080px;
        background-color: #f00;
        transform-origin: top left;
        margin-left: 50%;
      }
    </style>
  </head>
  <body style="overflow: hidden; width: 100vw; height: 100vh">
    <div class="demo1"></div>
  </body>

  <script>
    /**
     * 计算比例
     * @param {number} width - 设计图的宽度
     * @param {number} height - 设计图的高度
     * @param {HTMLElement} el - 需要应用比例的元素
     */
    const calculateRatio = (width, height, el) => {
      // 设计图的宽高
      const baseWidth = width;
      const baseHeight = height;
      // 设计图的比例
      const baseRate = parseFloat(baseWidth / baseHeight).toFixed(5);

      // 当前屏幕的比例
      const currentRate = parseFloat(
        window.innerWidth / window.innerHeight
      ).toFixed(5);

      // 用于存储计算后的宽度和高度比例
      const scale = {
        widthRatio: 1,
        heightRatio: 1,
      };

      // 根据当前屏幕比例和设计图比例计算适当的缩放比例
      if (currentRate > baseRate) {
        // 如果当前比例大于设计图比例,则根据高度计算比例
        scale.widthRatio = parseFloat(
          ((window.innerHeight * baseRate) / baseWidth).toFixed(5)
        );
        scale.heightRatio = parseFloat(
          (window.innerHeight / baseHeight).toFixed(5)
        );
      } else {
        // 如果当前比例小于或等于设计图比例,则根据宽度计算比例
        scale.heightRatio = parseFloat(
          (window.innerWidth / baseRate / baseHeight).toFixed(5)
        );
        scale.widthRatio = parseFloat(
          (window.innerWidth / baseWidth).toFixed(5)
        );
      }
      // 设置等比缩放或者放大
      el.style.transform = `scale(${scale.widthRatio}, ${scale.heightRatio}) translate(-50%, 0)`;
    };

    calculateRatio(1920, 1080, document.querySelector(".demo1"));

    window.addEventListener("resize", () => {
      calculateRatio(1920, 1080, document.querySelector(".demo1"));
    });
  </script>
</html>

240922142345.gif

总结

通过ui图的比例和当前屏幕显示的比例去计算需要缩放的大小倍数,如果当前的屏幕比例大于设计图的比例 那么就是宽度大于高度根据高度去计算缩放 反之则使用宽度去计算

image.png