// src/utils/scaleUtils.ts
import { onMounted, onBeforeUnmount, ref } from 'vue'
const DESIGN_WIDTH = 1920
const DESIGN_HEIGHT = 1080
const scaleStyle = ref('') // 缩放样式
// 导出一个函数,用于获取屏幕缩放比例
export function useScreenScale() {
// 定义配置,包括设计宽度和高度
const config = {
width: Number(DESIGN_WIDTH) || 1920,
height: Number(DESIGN_HEIGHT) || 1080,
}
// 更新缩放比例
const updateScale = () => {
// 初始化缩放比例
const scale = {
width: 1,
height: 1,
}
// 获取窗口宽度
const windowWidth = window.innerWidth
// 获取窗口高度
const windowHeight = window.innerHeight
const currentRate = parseFloat((windowWidth / windowHeight).toFixed(5)) // 屏幕比例
const baseProportion = parseFloat((config.width / config.height).toFixed(5)) // 设定比例
// 如果当前比例大于设定比例,则高度不变,宽度按比例缩放
if (currentRate > baseProportion) {
scale.height = parseFloat((windowHeight / config.height).toFixed(5))
scale.width = parseFloat(
((windowHeight * baseProportion) / config.width).toFixed(5)
)
scaleStyle.value = `scale(${scale.width}, ${scale.height})`
} else {
// 如果当前比例小于设定比例,则宽度不变,高度按比例缩放
scale.height = parseFloat(
(windowWidth / baseProportion / config.height).toFixed(5)
)
scale.width = parseFloat((windowWidth / config.width).toFixed(5))
scaleStyle.value = `scale(${scale.width}, ${scale.height})`
}
}
// 定义一个resize函数
const resize = () => {
// 设置一个定时器,延迟200毫秒后执行updateScale函数
setTimeout(() => {
updateScale()
}, 200)
}
onMounted(() => {
updateScale()
window.addEventListener('resize', resize)
})
onBeforeUnmount(() => {
window.removeEventListener('resize', resize)
})
return {
scaleStyle,
config,
}
}
<template>
<div class="container" :style="containerStyle">
<ScaleContainer>
<!-- 你的可视化大屏内容 -->
<Dashboard />
</ScaleContainer>
</div>
</template>
<script setup>
import ScaleContainer from './components/ScaleContainer.vue'
import Dashboard from './view/Dashboard.vue'
import { computed } from 'vue'
import { useScreenScale } from './components/BaseChart.ts'
const { scaleStyle, config } = useScreenScale()
const containerStyle = computed(() => {
return {
'--base-width': `${config.width}px`,
'--base-height': `${config.height}px`,
'--scale-style': scaleStyle.value,
}
})
</script>
<style lang="scss" scoped>
.container {
/* 父容器需要具体尺寸 */
margin: 0 auto;
}
</style>
<template>
<div class="scale-container">
<slot />
</div>
</template>
<script setup lang="ts"></script>
<style scoped>
.scale-container {
transform: var(--scale-style);
transform-origin: center top;
transition: transform 0.2s;
}
</style>