【前端可視化】大屏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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章