欢迎光临我的博客,我是努力挣钱的小鑫!目前正在杭州努|

努力挣钱的小鑫

园龄:4年10个月粉丝:36关注:8

【前端可视化】大屏scale适配vue3 hooks封装

body样式

body {
  position: relative;
  width: 1920px;
  height: 1080px;
  box-sizing: border-box;

  // scale 缩放中心 左上角
  transform-origin: left top;
}

useScalePage.js

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

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

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

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

  // 大屏的适配
  function triggerScale() {
    // 1.设计稿的尺寸
    let targetX = option.targetX || 1920;
    let targetY = option.targetY || 1080;
    let targetRatio = option.targetRatio || 16 / 9; // 宽高比率

    // 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.cssText = `width:${targetX}px; height:${targetY}px;transform: scale(${scaleRatio}) translateX(-50%); left: 50%`;
    } else {
      // 4.开始缩放网页
      document.body.style.cssText = `width:${targetX}px; height:${targetY}px; transform: scale(${scaleRatio})`;
    }
  }
}

使用

<template>
  <!-- 路由占位 -->
  <router-view />
</template>

<script setup>
import { RouterView } from 'vue-router';
import useScalePage from '@/hooks/useScalePage';

let option = {
  targetX: 1920,
  targetY: 1080,
  targetRatio: 16 / 9,
};
// 大屏适配
useScalePage(option);
</script>

<style scoped></style>
posted @   努力挣钱的小鑫  阅读(400)  评论(0编辑  收藏  举报
历史上的今天:
2020-04-28 【Element】table 组件出现表格线条不对齐的问题
2020-04-28 【Vscode】Elements in iteration expect to have 'v-bind:key' directives 报错
2020-04-28 【Git】创建子分支,合并分支并提交
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起