fei.wang
2024-05-09 2702116ca5e3cb39829a63e1959a85c2365129e1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { ref } from "vue";
  // * 堆代码 www.duidaima.com
export default function windowResize() {
 // * 指向最外层容器
 const screenRef = ref();
 // * 定时函数
 const timer = ref(0);
 // * 默认缩放值
 const scale = {
  width: "1",
  height: "1",
 };
    
 // * 设计稿尺寸(px)
 const baseWidth = 1920;
 const baseHeight = 1080;
 // * 需保持的比例(默认1.77778)
 const baseProportion = parseFloat((baseWidth / baseHeight).toFixed(5));
 const calcRate = () => {
  // 当前宽高比
  const currentRate = parseFloat(
   (window.innerWidth / window.innerHeight).toFixed(5)
  );
  if (screenRef.value) {
   if (currentRate > baseProportion) {
    // 表示更宽
    scale.width = (
     (window.innerHeight * baseProportion) /
     baseWidth
    ).toFixed(5);
    scale.height = (window.innerHeight / baseHeight).toFixed(5);
    screenRef.value.style.transform = `scale(${scale.width}, ${scale.height})`;
   } else {
    // 表示更高
    scale.height = (
     window.innerWidth /
     baseProportion /
     baseHeight
    ).toFixed(5);
    scale.width = (window.innerWidth / baseWidth).toFixed(5);
    screenRef.value.style.transform = `scale(${scale.width}, ${scale.height})`;
   }
  }
 };
 const resize = () => {
  clearTimeout(timer.value);
  timer.value = window.setTimeout(() => {
   calcRate();
  }, 200);
 };
 // 改变窗口大小重新绘制
 const windowDraw = () => {
  window.addEventListener("resize", resize);
 };
 // 改变窗口大小重新绘制
 const unWindowDraw = () => {
  window.removeEventListener("resize", resize);
 };
 return {
  screenRef,
  calcRate,
  windowDraw,
  unWindowDraw,
 };
}