可视化大屏scale适配方案

通过设置缩放比例,完成全屏适配

由于需要固定尺寸,所以需要内部子控件用定位实现布局。
需要在body中设置定位

body {
  position: relative;
  width: 1920px;
  height: 1080px;
  transform-origin: left top;
}

固定比例适配

import { onMounted, onUnmounted } from "vue";
import _ from "lodash";

/**
  大屏适配的 hooks
 */
export default function useScalePage(
  targetWidth = 1920,
  targetHeight = 1080,
  targetProportion = 16 / 9
) {
  const resizeFunc = _.throttle(function () {
    triggerScale(); // 动画缩放网页
  }, 100);

  onMounted(() => {
    triggerScale(); // 动画缩放网页
    window.addEventListener("resize", resizeFunc);
  });

  onUnmounted(() => {
    window.removeEventListener("resize", resizeFunc); // 释放
  });

  // 大屏的适配
  function triggerScale() {
    // 1.设计稿的尺寸
    let targetX = targetWidth;
    let targetY = targetHeight;
    let targetRatio = targetProportion; // 宽高比率

    // 2.拿到当前设备(浏览器)的宽度
    let currentX =
      document.documentElement.clientWidth || document.body.clientWidth;
    let currentY =
      document.documentElement.clientHeight || document.body.clientHeight;

    // 3.计算缩放比例
    let scaleRatio = currentX / targetX; // 参照宽度进行缩放 ( 默认情况 )
    let currentRatio = currentX / currentY; // 宽高比率

    // 超宽屏
    if (currentRatio > targetRatio) {
      // 4.开始缩放网页
      scaleRatio = currentY / targetY; // 参照高度进行缩放
      document.body.style = `width:${targetX}px; height:${targetY}px;transform: scale(${scaleRatio}) translateX(-50%); left: 50%`;
    } else {
      // 4.开始缩放网页
      document.body.style = `width:${targetX}px; height:${targetY}px; transform: scale(${scaleRatio})`;
    }
  }
}

等宽适配

import { onMounted, onUnmounted } from "vue";
import _ from "lodash";

/**
  大屏适配的 hooks
 */
export default function useScalePageAllWidth() {
  const resizeFunc = _.throttle(function () {
    triggerScale(); // 动画缩放网页
  }, 100);

  onMounted(() => {
    triggerScale(); // 动画缩放网页
    window.addEventListener("resize", resizeFunc);
  });

  onUnmounted(() => {
    window.removeEventListener("resize", resizeFunc); // 释放
  });

  // 大屏的适配
  // 用于执行缩放和拉伸的函数
  function triggerScale(targetWidth = 1920, targetHeight = 1080) {
    const screenWidth = document.documentElement.clientWidth;
    const scaleX = screenWidth / targetWidth;
    // 设置 body 元素的样式
    document.body.style.width = targetWidth + "px";
    document.body.style.height = targetHeight + "px";
    document.body.style.transform = `scale(${scaleX})`;
    document.body.style.transformOrigin = "top left";
  }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容