大屏可视化之动态 rem 方案

222 阅读2分钟

在做大屏可视化项目时,需要考虑不同的屏幕尺寸,所以需要使用动态适配的方案来尽可能的保证大部分的主流显示器都能正常展示。

要求

假设设计图比例为 16 / 9,需要在不同屏幕尺寸(浏览器视口尺寸)下,大屏页面都能保证比例不变,元素和字体大小根据屏幕大小自动适配。

如何适配屏幕

  • 算法: image.png
  • Wp 为页面有效宽度,Hp 为页面有效高度
  • 如果屏幕很宽,页面左右居中,如果屏幕很高,页面上下居中,四周留白即可
  • 然后在 head 里用 JS 设置 1rem = Wp / 100

实施步骤

首先获取浏览器的宽和高

const clientWidth = document.documentElement.clientWidth
const clientHeight = document.documentElement.clientHeight

根据宽高比代入公式

window.pageWidth = clientWidth / clientHeight > 16 / 9 ? clientHeight * (16 / 9) : clientWidth
const pageHeight = pageWidth / (16 / 9)

然后在 head 里用 JS 设置 1rem = Wp / 100

const string = `<style>html{
  font-size: ${pageWidth / 100}px
}</style>`
document.write(string)

在 body 中将获得的尺寸给根组件

<div id="root"></div>
<script>
  root.style.width = pageWidth + 'px'
  root.style.height = pageHeight + 'px'
</script>

给根组件样式,使其左右居中

#root {
  margin: 0 auto;
}

给根组件加上marginTop,使其上下居中

<div id="root"></div>
<script>
  root.style.marginTop = (clientHeight - pageHeight) / 2 + 'px'
</script>

效果如下图蓝色区域: 1679673407076.png 随意改变窗口大小,刷新之后页面始终保持水平垂直居中,而且页面元素大小自适应,页面字体始终为 pageWidth / 100 px,也就是 1rem。

下面在讲一下如何在上图的蓝色区域中制作一个div,因为这个div需要适配所有屏幕,所以不能使用像素px,只能写成rem

像素不能用怎么办

  • 用 rem image.png
  • 假设某 div 在设计稿中长 100px,设计稿宽度 1920px
  • 那么该 div 在页面中长为 100 / 1920 * 100rem
  • 最后可以写一个 px() 函数来计算 100px 对应的 rem

实施步骤

获取这个div在设计中的宽高以及设计的宽高,以此获得最终的宽高

.x {
  width: 367 / 2420 * 100rem;
  height: 315 / 2420 * 100rem;
  border: 2px solid red;
}

效果如下: 1679673457524.png 随意改变窗口大小,红框区域都随着蓝色区域的变化而变化,它永远是占16:9蓝色屏幕的固定比例。