背景
在做大屏可视化项目的时候,一般设计稿会设计成1920 * 1080,但是页面写死1920 * 1080在2k、4k等分辨率的屏幕下是不适配的。
方案一:css3的缩放属性transform以及scale()
在做项目之前我们需要搞清楚客户的数据可视化平台需要在什么屏幕下展示,确定了实际屏幕比例,按照实际屏幕比例选择一个设计稿尺寸进行设计,设计稿出来后前端严格按照设计稿px进行开发页面即可。代码如下:
ScreenScale.vue
<template>
<div
class="screen-scale"
:style="style"
>
<slot></slot>
</div>
</template>
<script>
export default {
props: {
width: {
type: Number,
default: 1920 //设计稿的宽度
},
height: {
type: Number,
default: 1080 //设计稿的高度
}
},
data() {
return {
scale: 1
};
},
computed: {
style() {
return `transform:scale(${
this.scale}) translate(-50%, -50%);
-ms-transform:scale(${
this.scale}) translate(-50%, -50%);
-moz-transform:scale(${
this.scale}) translate(-50%, -50%);
-webkit-transform:scale(${
this.scale}) translate(-50%, -50%);
-o-transform:scale(${
this.scale}) translate(-50%, -50%);
width:${
this.width}px;
height:${
this.height}px;`;
}
},
methods: {
getScale() {
//计算出缩放比
let ww = window.innerWidth / this.width;
let wh = window.innerHeight / this.height;
this.scale = ww < wh ? ww : wh;
}
},
mounted() {
this.getScale();
window.addEventListener('resize', this.getScale);
},
beforeDestroy() {
window.removeEventListener('resize', this.getScale);
}
};
</script>
<style scoped lang="less">
.screen-scale {
transform-origin: 0 0;
position: absolute;
left: 50%;
top: 50%;
transition: 0.3s;
overflow: hidden;
}
</style>
App.vue
<template>
<div id="app">
<ScreenScale>
<RouterView />
</ScreenScale>
</div>
</template>
<script setup>
import ScreenScale from '@/components/ScreenScale.vue';
</script>
<style>
* {
box-sizing: border-box;
}
html,
body {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
background-color: #0c1940;
}
#app {
height: 100%;
width: 100%;
}
</style>
优点:此种方法的好处就是保证字体、图片等不被拉伸变形。’
缺点:在与设计稿比例不同的屏幕下会左右或者上下出现留白。
偷懒方法:v-scale-screen
插件:Vue大屏自适应终极解决方案
注意点:如果使用到类似antd
的Modal
弹窗,由于Modal
默认是挂载在 body 上的,这就导致ScreenScale 组件不能作用在 Modal 上,解决办法就是把 Modal 挂载到组件以内的位置上。参考:antdv Modal(对话框)指定挂载节点 demo