一、项目主页,一般是App.vue
<template>
<NConfigProvider :locale="zhCN" :theme-overrides="themeOverrides" :date-locale="dateZhCN">
<AppProvider>
<div class="app">
<RouterView />
</div>
</AppProvider>
</NConfigProvider>
</template>
<script lang="ts" setup>
import { zhCN, dateZhCN } from 'naive-ui'
import { AppProvider } from '@/components/Application'
import themeOverrides from '@/assets/theme.json'
import * as echarts from 'echarts'
import { provide } from 'vue'
provide('echarts', echarts)
</script>
<style lang="less">
@import '@/assets/less/common.less';
// 其他的不用管 这里主要是为了防止出现滚动条
html,
body {
overflow: hidden !important;
}
// 这里才是设置大屏外层容器最重要的
.app {
width: 100vw;
height: 100vh;
background-color: #000;
overflow: hidden !important;
}
</style>
二、封装方法,在utils文件夹里面新建scalingRatio.ts
import { ref } from 'vue'
export default function useDraw() {
// 指向最外层容器
const appRef = ref()
// 定时函数
const timer = ref(0)
// 默认缩放值
const scale = {
width: '1',
height: '1'
}
// 设计稿尺寸(px)
const baseWidth = 1920
const baseHeight = 1080
// 需保持的比例
const baseProportion = parseFloat((baseWidth / baseHeight).toFixed(5))
const calcRate = () => {
// 当前宽高比
const currentRate = parseFloat((window.innerWidth / window.innerHeight).toFixed(5))
if (appRef.value) {
if (currentRate > baseProportion) {
// 表示更宽
scale.width = ((window.innerHeight * baseProportion) / baseWidth).toFixed(5)
scale.height = (window.innerHeight / baseHeight).toFixed(5)
var ratioX = window.innerWidth / 1920 //此处的宽高根据自己屏幕的比例修改即可
var ratioY = window.innerHeight / 1080
appRef.value.style.transform = `scale(${ratioX}, ${ratioY}) translate(-50%, -50%)`
} else {
// 表示更高
scale.height = (window.innerWidth / baseProportion / baseHeight).toFixed(5)
scale.width = (window.innerWidth / baseWidth).toFixed(5)
var ratioX = window.innerWidth / 1920 //此处的宽高根据自己屏幕的比例修改即可
var ratioY = window.innerHeight / 1080
appRef.value.style.transform = `scale(${ratioX}, ${ratioY}) translate(-50%, -50%)`
}
}
}
const resize = () => {
clearTimeout(timer.value)
timer.value = setTimeout(() => {
calcRate()
}, 200)
}
// 改变窗口大小重新绘制
const windowDraw = () => {
window.addEventListener('resize', resize)
window.addEventListener('pageshow', resize)
}
// 改变窗口大小重新绘制
const unWindowDraw = () => {
window.removeEventListener('resize', resize)
window.removeEventListener('pageshow', resize)
}
return {
appRef,
calcRate,
windowDraw,
unWindowDraw
}
}
三、在大屏主页引入使用
大屏html结构
<div class="big-data-page" ref="appRef">
</div>
<style lang='scss'>
.big-data-page {
// 设置定位让基点位于屏设备中心点
position: fixed;
left: 50%;
top: 50%;
width: 1920px;
height: 1080px;
background-color: red;
// 设置缩放基点为左上角 不能以盒子中心点
transform-origin: left top;
}
<style>
引入封装好的方法
import useDraw from '@/utils/scalingRatio'
const { appRef, calcRate, windowDraw, unWindowDraw } = useDraw()
onMounted(() => {
windowDraw()
calcRate()
})
onUnmounted(() => {
unWindowDraw()
})