大屏适配的一次尝试

188 阅读1分钟

调研

在考虑大屏适配得时候,也去网上看过一些方案,

  • 1.用一些相对单位rem,vw,vh什么得
  • 2.借助transform scale属性来玩

需求

参考自己的项目,

  • 一个是主要是在大屏展示的尺寸比例不确定
  • 二是用到大量得echarts,我不想去处理echarts里面的单位,太过于麻烦,甚至还用到了很多ui库的组件

实操

如果是方案一,我需要去转换项目中很多的px单位

最终为了简单,还是用transform scale属性来玩这次的适配


简单的封装了个fullScreen组件

<template>
	<div class="screen-wrapper">
		<div class="screen" id="screen">
			<div :key='update' class="screen-container">
				<slot></slot>
			</div>
		</div>
	</div>
</template>


<script>
	/**
	支持按照比例缩放,默认1920-1080  1920*n-1080*n
	例如 1920*1080  
        **/
	export default {
		name: 'scale-container',
		data() {
			return {
				update: 0
			}
		},
		mounted() {
			// 初始化自适应  ----在刚显示的时候就开始适配一次
			this.handleScreenAuto();
			// 绑定自适应函数   ---防止浏览器栏变化后不再适配
			window.onresize = () => {
				this.handleScreenAuto()
				
			};
		},
		methods: {
			/**
			@数据大屏自适应函数
			设计稿 1920 1080 默认屏幕高宽比 1920/1080
			为防止变形严重,高宽比建议在一定数值
			**/ 
			handleScreenAuto() {				
				//当前屏幕的宽比计算
				const wh=document.documentElement.clientWidth /document.documentElement.clientHeight
				//设置默认值
				const designDraftWidth = 1920; //设计稿的宽度
				const designDraftHeight = designDraftWidth/wh; //设计稿的高度
				document.querySelector('#screen').style.width = designDraftWidth + 'px'
				document.querySelector('#screen').style.height = designDraftHeight + 'px'
				
				// 根据屏幕的变化适配的比例
				const scale =
					wh <
					designDraftWidth / designDraftHeight ?
					document.documentElement.clientWidth / designDraftWidth :
					document.documentElement.clientHeight / designDraftHeight;
				document.querySelector('#screen').style.transform = `scale(${scale}) translate(-50%, -50%)`;
			
				setTimeout(()=>{
					this.update+=1
				},300)
				
			}
		}
	}

</script>

<style lang="less">
	.screen-wrapper {
		position: fixed;
		top:0;
		left: 0;
		height: 100% !important;
		width: 100% !important;

		.screen {
			transform-origin: 0 0;
			position: absolute;
			left: 50%;
			top: 50%;
			transition: .3s;
			z-index: 999;
		}

		.screen-container {
			height: 100%;
			width: 100%;
		}
	}

</style>