在日常前端开发中,大屏项目是每个前端开发者必备技能,但是目前设备尺寸大小和分辨率都不相同,所以大屏适配成了一个头疼的问题。看到网上的实现方案有rem,flexible,zoom,百分比,总感觉没那么完美,于是自己研究了一下也借鉴了网上大神的方法,实现了一下这三种大屏适配方案,在实际开发中可以借鉴使用
第一种:使用css属性scale缩放来适配(简单,易上手)
gitee地址:大屏可视化模板: 大屏可视化模板。利用scale来分辨率适配
我把关键代码封装成了组件,使用的时候直接套在大屏页面就可以实现
<template>
<div class="scale-box">
<slot></slot>
</div>
</template>
<script setup>
import { ref, onMounted, defineProps } from 'vue'
const width = ref(null), //设计宽度
height = ref(null), //设计高度
scale = ref(null)
const props = defineProps({
width: {
type: String,
default: '1920px',
},
height: {
type: String,
default: '1080px',
},
})
const init = () => {
setScale()
('resize', setScale)
}
const setScale = () => {
let ww = /
let wh = /
= ww < wh ? ww : wh
}
init()
</script>
<style scoped>
.scale-box {
width: v-bind('');
height: v-bind('');
transform: scale(v-bind(scale)) translate(-50%, -50%);
transform-origin: 0 0;
position: absolute;
left: 50%;
top: 50%;
transition: 0.3s;
}
</style>
第二种:固定缩放比
gitee地址:大屏可视化模板固定尺寸: 大屏可视化模板固定尺寸
关键代码:
export const fitScreen = () => {
const body =
const bodyWidth =
const bodyHeight =
const realRatio = bodyWidth / bodyHeight
const designRatio = 16 / 9
const scaleRate = realRatio > designRatio ? bodyHeight / 1080 : bodyWidth / 1920
const app:any= ('.bigScreen')
app &&
( = 'left top') &&
( = `scale(${scaleRate}) translateX(-50%)`) &&
( = `${bodyWidth / scaleRate}px`)
}
= () => {
fitScreen('.Layout');
};
第三种:缩放+铺满全屏+百分比
gitee地址:大屏可视化自动拉伸模板: 大屏可视化自动拉升模板
关键代码:
<script setup>
import { ref, reactive, onMounted, onUnmounted } from "vue";
// * 默认缩放值
const scale = reactive({
width: "1",
height: "1",
});
// * 设计稿尺寸(px)
const baseWidth = 1920;
const baseHeight = 1080;
// * 需保持的比例
const baseProportion = parseFloat((baseWidth / baseHeight).toFixed(5));
let drawTiming = ref(null);
const appRef = ref();
const calcRate = () => {
if (!) return;
// 当前宽高比
const browserRoom = getZoom();
// 当前宽高比
/**
* 1. 先将宽高乘上浏览器缩放倍数x
* 2. 再将整个页面用scale缩放 1/x 倍
* 在视觉上,就感觉页面没有缩放
*/
// 宽高
const w = * browserRoom;
const h = * browserRoom;
// scale缩放比例
const scl = parseFloat((1 / browserRoom).toFixed(5));
// 页面重绘处理
= `${w}px`;
= `${h}px`;
= `scale(${scl}, ${scl}) translate(-50%, -50%)`;
};
const getZoom = () => {
let ratio = 0,
screen = ,
ua = ();
if ( !== undefined) {
ratio = ;
} else if (~("msie")) {
if ( && ) {
ratio = / ;
}
} else if (
!== undefined &&
!== undefined
) {
ratio = / ;
}
if (ratio) {
ratio = (ratio * 100);
}
return parseFloat(ratio / 100).toFixed(2);
};
// 窗口大小变化
const resize = () => {
clearTimeout();
= setTimeout(() => {
calcRate();
}, 200);
};
onMounted(() => {
calcRate();
("resize", resize);
});
onUnmounted(() => {
("resize", resize);
});
</script>
以上就是我总结的大屏可视化屏幕适配方案,有好的想法可以和我交流,一起进步!!!