大前端数据大屏可视化-适配各种分辨率
1.采用scale的缩放,结合设计图的1920和1080(能实现全屏,没有白边,简单直接)
// 通过scale实现大屏适配function screen() {let w = window.innerWidth;let h = window.innerHeight;console.log(w, h);if (w != 1920 || h != 1080) {let scale = `scale(${w / 1920}, ${h / 1080})`;document.body.style.transform = scale;document.body.style.transformOrigin = "0 0";document.body.style.width = "1920px";document.body.style.height = "1080px";} else {document.body.style.transform = "scale(1, 1)";document.body.style.width = "100%";document.body.style.height = "100%";}}window.onresize = function () {screen();};
缺点:会出现字体图标会失真,如果使用three.js可能有点问题,可能需要配置拾取坐标(利用scale的变量)
2.采用scale,和第二个scale有一些差别(能接受左右有留白)
封装的js代码如下:
import { ref } from "vue";export default function windowResize() {// * 指向最外层容器const screenRef = ref();// * 定时函数const timer = ref(0);// * 默认缩放值const scale = {width: "1",height: "1",};// * 设计稿尺寸(px)const baseWidth = 1920;const baseHeight = 1080;// * 需保持的比例(默认1.77778)const baseProportion = parseFloat((baseWidth / baseHeight).toFixed(5));const calcRate = () => {// 当前宽高比const currentRate = parseFloat((window.innerWidth / window.innerHeight).toFixed(5));if (screenRef.value) {if (currentRate > baseProportion) {// 表示更宽scale.width = ((window.innerHeight * baseProportion) /baseWidth).toFixed(5);// 计算宽度缩放比例scale.height = (window.innerHeight / baseHeight).toFixed(5);screenRef.value.style.transform = `scale(${scale.width}, ${scale.height})`;} else {// 表示更高scale.height = (window.innerWidth /baseProportion /baseHeight).toFixed(5);// 计算高度缩放比例scale.width = (window.innerWidth / baseWidth).toFixed(5);screenRef.value.style.transform = `scale(${scale.width}, ${scale.height})`;}}};const resize = () => {clearTimeout(timer.value);timer.value = window.setTimeout(() => {calcRate();}, 200);};// 改变窗口大小重新绘制const windowDraw = () => {window.addEventListener("resize", resize);};// 改变窗口大小重新绘制const unWindowDraw = () => {window.removeEventListener("resize", resize);};return {screenRef,calcRate,windowDraw,unWindowDraw,};
}
vue3中调用代码如下:
注意:
(1)需要禁用body的滚动条overflow: hidden;如果不禁用的话,按下F12会出现滚动条,导致右边出现白条
(2)左右留白可以用外面盒子包含里面盒子,外面盒子用背景色或者图片,减小留白影响