一次搞懂數(shù)據(jù)大屏適配方案 (vw vh、rem、scale)
大廠技術(shù) 高級前端 Node進階
點擊上方 程序員成長指北,關(guān)注公眾號
回復(fù)1,加入高級Node交流群
當接到可視化大屏需求時,你是否會有以下疑問??如何做一款定制化的數(shù)據(jù)大屏? 開發(fā)可視化數(shù)據(jù)大屏如何做自適應(yīng)? vm vh、rem、scale 到底哪種比較好? 時間不夠,有沒有偷懶的方法?
最近在公司開發(fā)了一個可視化大屏,開發(fā)定制化大屏,大家可能都一個感受,開發(fā)大屏主要是兩方面的工作:
大屏之關(guān)鍵-前期的自適應(yīng)適配根據(jù) ui 稿繪制圖表,調(diào)細節(jié)
而解決了適配問題后,后面就只是一個慢工出細活,耗時間的事情了。
適配方案分析
看了網(wǎng)上的各種方案,目前大家采用的大概有 3 種??
| 方案 | 實現(xiàn)方式 | 優(yōu)點 | 缺點 |
|---|---|---|---|
| vm vh | 1.按照設(shè)計稿的尺寸,將px按比例計算轉(zhuǎn)為vw和vh | 1.可以動態(tài)計算圖表的寬高,字體等,靈活性較高 2.當屏幕比例跟 ui 稿不一致時,不會出現(xiàn)兩邊留白情況 | 1.每個圖表都需要單獨做字體、間距、位移的適配,比較麻煩 |
| scale | 1.通過 scale 屬性,根據(jù)屏幕大小,對圖表進行整體的等比縮放 | 1.代碼量少,適配簡單 2.一次處理后不需要在各個圖表中再去單獨適配 | 1.因為是根據(jù) ui 稿等比縮放,當大屏跟 ui 稿的比例不一樣時,會出現(xiàn)周邊留白情況 2.當縮放比例過大時候,字體會有一點點模糊,就一點點 3.當縮放比例過大時候,事件熱區(qū)會偏移。 |
| rem + vm vh | 1.獲得 rem 的基準值 2.動態(tài)的計算html根元素的font-size 3.圖表中通過 vm vh 動態(tài)計算字體、間距、位移等 | 1.布局的自適應(yīng)代碼量少,適配簡單 | 1.因為是根據(jù) ui 稿等比縮放,當大屏跟 ui 稿的比例不一樣時,會出現(xiàn)周邊留白情況 2.圖表需要單個做字體、間距、位移的適配 |
以上 3 種方案在實際應(yīng)用中該怎么選擇視具體情況而定,也有看到大家說自適應(yīng)在地圖的適配中會有一些兼容問題,我這邊還沒有實踐過。
如果想簡單,客戶能同意留白,選用 scale即可如果需要兼容不同比例的大屏,并且想在不同比例中都有比較好的效果,圖表占滿屏幕,類似于移動端的響應(yīng)式,可以采用 vm vh 的方案 至于 rem,個人覺得就是 scale 和 vm vh 的綜合,最終的效果跟 scale差不多
接下來介紹下三種方案的具體實現(xiàn),方案中的代碼都以 vue2.0 和 vue-cli3 搭建的 vue 項目為例,因為是 demo,圖表的一些細節(jié)就沒有過多細致的調(diào)整了
方案一:vw vh
上效果

當屏幕的尺寸比例剛好是 16:9 時

當屏幕的尺寸比例大于 16:9 時

當屏幕的尺寸比例小于 16:9 時

實現(xiàn)思路
按照設(shè)計稿的尺寸,將px按比例計算轉(zhuǎn)為vw和vh,轉(zhuǎn)換公式如下
假設(shè)設(shè)計稿尺寸為 1920*1080(做之前一定問清楚 ui 設(shè)計稿的尺寸)
即:
網(wǎng)頁寬度=1920px
網(wǎng)頁高度=1080px
我們都知道
網(wǎng)頁寬度=100vw
網(wǎng)頁寬度=100vh
所以,在 1920px*1080px 的屏幕分辨率下
1920px = 100vw
1080px = 100vh
這樣一來,以一個寬 300px 和 200px 的 div 來說,其所占的寬高,以 vw 和 vh 為單位,計算方式如下:
vwDiv = (300px / 1920px ) * 100vw
vhDiv = (200px / 1080px ) * 100vh
所以,就在 1920*1080 的屏幕分辨率下,計算出了單個 div 的寬高
當屏幕放大或者縮小時,div 還是以 vw 和 vh 作為寬高的,就會自動適應(yīng)不同分辨率的屏幕
復(fù)制代碼
話不多說,上代碼
css 方案 - sass
util.scss
// 使用 scss 的 math 函數(shù),https://sass-lang.com/documentation/breaking-changes/slash-div
@use "sass:math";
// 默認設(shè)計稿的寬度
$designWidth: 1920;
// 默認設(shè)計稿的高度
$designHeight: 1080;
// px 轉(zhuǎn)為 vw 的函數(shù)
@function vw($px) {
@return math.div($px, $designWidth) * 100vw;
}
// px 轉(zhuǎn)為 vh 的函數(shù)
@function vh($px) {
@return math.div($px, $designHeight) * 100vh;
}
復(fù)制代碼
路徑配置只需在vue.config.js里配置一下utils.scss的路徑,就可以全局使用了
vue.config.js
const path = require("path");
function resolve(dir) {
return path.join(__dirname, dir);
}
module.exports = {
publicPath: "",
configureWebpack: {
name: "app name",
resolve: {
alias: {
"@": resolve("src"),
},
},
},
css: {
// 全局配置 utils.scs,詳細配置參考 vue-cli 官網(wǎng)
loaderOptions: {
sass: {
prependData: `@import "@/styles/utils.scss";`,
},
},
},
};
復(fù)制代碼
在 .vue 中使用
<template>
<div class="box">
</div>
</template>
<script>
export default{
name: "Box",
}
</script>
<style lang="scss" scoped="scoped">
/*
直接使用 vw 和 vh 函數(shù),將像素值傳進去,得到的就是具體的 vw vh 單位
*/
.box{
width: vw(300);
height: vh(100);
font-size: vh(16);
background-color: black;
margin-left: vw(10);
margin-top: vh(10);
border: vh(2) solid red;
}
</style>
復(fù)制代碼
css 方案 - less
utils.less
@charset "utf-8";
// 默認設(shè)計稿的寬度
@designWidth: 1920;
// 默認設(shè)計稿的高度
@designHeight: 1080;
.px2vw(@name, @px) {
@{name}: (@px / @designWidth) * 100vw;
}
.px2vh(@name, @px) {
@{name}: (@px / @designHeight) * 100vh;
}
.px2font(@px) {
font-size: (@px / @designWidth) * 100vw;
}
復(fù)制代碼
路徑配置在vue.config.js里配置一下utils.less
const path = require("path");
function resolve(dir) {
return path.join(__dirname, dir);
}
module.exports = {
publicPath: "",
configureWebpack: {
name: "app name",
resolve: {
alias: {
"@": resolve("src"),
},
},
},
css: {
// 全局配置utils.scss
loaderOptions: {
less: {
additionalData: `@import "@/styles/utils.less";`,
},
},
},
};
復(fù)制代碼
在 .vue 文件中使用
<template>
<div class="box">
</div>
</template>
<script>
export default{
name: "Box",
}
</script>
<style lang="less" scoped="scoped">
/*
直接使用 vw 和 vh 函數(shù),將像素值傳進去,得到的就是具體的 vw vh單位
*/
.box{
.px2vw(width, 300);
.px2vh(height, 100);
.px2font(16);
.px2vw(margin-left, 300);
.px2vh(margin-top, 100);
background-color: black;
}
</style>
復(fù)制代碼
定義 js 樣式處理函數(shù)
// 定義設(shè)計稿的寬高
const designWidth = 1920;
const designHeight = 1080;
// px轉(zhuǎn)vw
export const px2vw = (_px) => {
return (_px * 100.0) / designWidth + 'vw';
};
export const px2vh = (_px) => {
return (_px * 100.0) / designHeight + 'vh';
};
export const px2font = (_px) => {
return (_px * 100.0) / designWidth + 'vw';
};
復(fù)制代碼
屏幕變化后,圖表自動調(diào)整
這種使用方式有個弊端,就是屏幕尺寸發(fā)生變化后,需要手動刷新一下才能完成自適應(yīng)調(diào)整
為了解決這個問題,你需要在各個圖表中監(jiān)聽頁面尺寸變化,重新調(diào)整圖表,在 vue 項目中,也可以借助element-resize-detector,最好封裝個 resize 的指令,在各圖表中就只要使用該指令就可以了,畢竟作為程序員,能偷懶就偷懶
安裝 element-resize-detector
npm install element-resize-detector --save
引入工具包在組件中使用或者在單獨的 js 中使用
import resizeDetector from 'element-resize-detector'
封裝 directive
// directive.js
import * as ECharts from "echarts";
import elementResizeDetectorMaker from "element-resize-detector";
import Vue from "vue";
const HANDLER = "_vue_resize_handler";
function bind(el, binding) {
el[HANDLER] = binding.value
? binding.value
: () => {
let chart = ECharts.getInstanceByDom(el);
if (!chart) {
return;
}
chart.resize();
};
// 監(jiān)聽綁定的div大小變化,更新 echarts 大小
elementResizeDetectorMaker().listenTo(el, el[HANDLER]);
}
function unbind(el) {
// window.removeEventListener("resize", el[HANDLER]);
elementResizeDetectorMaker().removeListener(el, el[HANDLER]);
delete el[HANDLER];
}
// 自定義指令:v-chart-resize 示例:v-chart-resize="fn"
Vue.directive("chart-resize", { bind, unbind });
復(fù)制代碼
main.js 中引入
import '@/directive/directive';
復(fù)制代碼
html 代碼
<template>
<div class="linechart">
<div ref="chart" v-chart-resize class="chart"></div>
</div>
</template>
復(fù)制代碼
這里要注意的是,圖表中如果需要 tab 切換動態(tài)更新圖表數(shù)據(jù),在更新數(shù)據(jù)時一定不要用 echarts 的 dispose 方法先將圖表移除,再重新繪制,因為 resize 指令中掛載到的圖表實例還是舊的,就監(jiān)聽不到新的 chart 元素的 resize 了,更新數(shù)據(jù)只需要用 chart 的 setOption 方法重新設(shè)置配置項即可。
圖表字體、間距、位移等尺寸自適應(yīng)
echarts 的字體大小只支持具體數(shù)值(像素),不能用百分比或者 vw 等尺寸,一般字體不會去做自適應(yīng),當寬高比跟 ui 稿比例出入太大時,會出現(xiàn)文字跟圖表重疊的情況
這里我們就需要封裝一個工具函數(shù),來處理圖表中文字自適應(yīng)了??
默認情況下,這里以你的設(shè)計稿是 1920*1080 為例,即網(wǎng)頁寬度是 1920px (做之前一定問清楚 ui 設(shè)計稿的尺寸) 把這個函數(shù)寫在一個單獨的工具文件 dataUtil.js里面,在需要的時候調(diào)用其原理是計算出當前屏幕寬度和默認設(shè)計寬度的比值,將原始的尺寸乘以該值 另外,其它 echarts 的配置項,比如間距、定位、邊距也可以用該函數(shù)
編寫 dataUtil.js 工具函數(shù)
// Echarts圖表字體、間距自適應(yīng)
export const fitChartSize = (size,defalteWidth = 1920) => {
let clientWidth = window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth;
if (!clientWidth) return size;
let scale = (clientWidth / defalteWidth);
return Number((size*scale).toFixed(3));
}
復(fù)制代碼
將函數(shù)掛載到原型上
import {fitChartSize} from '@src/utils/dataUtil.js'
Vue.prototype.fitChartFont = fitChartSize;
復(fù)制代碼
這樣你可以在 .vue文件中直接使用this.fitChartSize()調(diào)用
<template>
<div class="chartsdom" ref="chart" v-chart-resize></div>
</template>
<script>
export default {
name: "dashboardChart",
data() {
return {
option: null,
};
},
mounted() {
this.getEchart();
},
methods: {
getEchart() {
let myChart = this.$echarts.init(this.$refs.chart);
const option = {
backgroundColor: "transparent",
tooltip: {
trigger: "item",
formatter: "{a} <br/> : {c}%",
},
grid: {
left: this.fitChartSize(10),
right: this.fitChartSize(20),
top: this.fitChartSize(20),
bottom: this.fitChartSize(10),
containLabel: true,
},
calculable: true,
series: [
{
color: ["#0db1cdcc"],
name: "計劃投入",
type: "funnel",
width: "45%",
height: "70%",
x: "5%",
minSize: "10%",
funnelAlign: "right",
center: ["50%", "50%"], // for pie
data: [
{
value: 30,
name: "下單30%",
},
{
value: 55,
name: "咨詢55%",
},
{
value: 65,
name: "點擊65%",
},
{
value: 60,
name: "訪問62%",
},
{
value: 80,
name: "展現(xiàn)80%",
},
].sort(function (a, b) {
return a.value - b.value;
}),
roseType: true,
label: {
normal: {
formatter: function () {},
position: "inside",
},
},
itemStyle: {
normal: {
borderWidth: 0,
shadowBlur: this.fitChartSize(20),
shadowOffsetX: 0,
shadowOffsetY: this.fitChartSize(5),
shadowColor: "rgba(0, 0, 0, 0.3)",
},
},
},
{
color: ["#0C66FF"],
name: "實際投入",
type: "funnel",
width: "45%",
height: "70%",
x: "50%",
minSize: "10%",
funnelAlign: "left",
center: ["50%", "50%"], // for pie
data: [
{
value: 35,
name: "下單35%",
},
{
value: 40,
name: "咨詢40%",
},
{
value: 70,
name: "訪問70%",
},
{
value: 90,
name: "點擊90%",
},
{
value: 95,
name: "展現(xiàn)95%",
},
].sort(function (a, b) {
return a.value - b.value;
}),
roseType: true,
label: {
normal: {
position: "inside",
},
},
itemStyle: {
normal: {
borderWidth: 0,
shadowBlur: this.fitChartSize(20),
shadowOffsetX: 0,
shadowOffsetY: this.fitChartSize(5),
shadowColor: "rgba(0, 0, 0, 0.3)",
},
},
},
],
};
myChart.setOption(option, true);
},
},
beforeDestroy() {},
};
</script>
<style lang="scss" scoped>
.chartsdom {
width: 100%;
height: 100%;
}
</style>
復(fù)制代碼
方案二:scale
通過 css 的 scale 屬性,根據(jù)屏幕大小,對圖表進行整體的等比縮放,從而達到自適應(yīng)效果
上效果

當屏幕的尺寸比例剛好是 16:9 時,頁面能剛好全屏展示,內(nèi)容占滿顯示器

當屏幕的尺寸比例小于 16:9 時,頁面上下留白,左右占滿并上下居中,顯示比例保持 16:9

當屏幕尺寸比例大于 16:9 時,頁面左右留白,上下占滿并居中,顯示比例保持 16:9

話不多說,上代碼
html 部分
<div className="screen-wrapper">
<div className="screen" id="screen">
</div>
</div>
復(fù)制代碼
js 部分
<script>
export default {
mounted() {
// 初始化自適應(yīng) ----在剛顯示的時候就開始適配一次
handleScreenAuto();
// 綁定自適應(yīng)函數(shù) ---防止瀏覽器欄變化后不再適配
window.onresize = () => handleScreenAuto();
},
deleted() {
window.onresize = null;
},
methods: {
// 數(shù)據(jù)大屏自適應(yīng)函數(shù)
handleScreenAuto() {
const designDraftWidth = 1920; //設(shè)計稿的寬度
const designDraftHeight = 960; //設(shè)計稿的高度
// 根據(jù)屏幕的變化適配的比例
const scale =
document.documentElement.clientWidth /
document.documentElement.clientHeight <
designDraftWidth / designDraftHeight
? document.documentElement.clientWidth / designDraftWidth
: document.documentElement.clientHeight / designDraftHeight;
// 縮放比例
document.querySelector(
'#screen',
).style.transform = `scale(${scale}) translate(-50%, -50%)`;
},
},
};
</script>
復(fù)制代碼
css部分
/*
除了設(shè)計稿的寬高是根據(jù)您自己的設(shè)計稿決定以外,其他復(fù)制粘貼就完事
*/
.screen-root {
height: 100%;
width: 100%;
.screen {
display: inline-block;
width: 1920px; //設(shè)計稿的寬度
height: 960px; //設(shè)計稿的高度
transform-origin: 0 0;
position: absolute;
left: 50%;
top: -50%;
}
}
復(fù)制代碼
實現(xiàn)思路
如何縮放
當屏幕寬高比 < 設(shè)計稿寬高比,我們需要縮放的比例是屏幕寬度 / 設(shè)計稿寬度當屏幕寬高比 > 設(shè)計稿寬高比,我們需要縮放的比例是屏幕高度 / 設(shè)計稿高度
const scale = document.documentElement.clientWidth / document.documentElement.clientHeight < designDraftWidth / designDraftHeight ?
(document.documentElement.clientWidth / designDraftWidth) :
(document.documentElement.clientHeight / designDraftHeight);
復(fù)制代碼
如果我們拿到的設(shè)計稿寬高為: 1920 * 960 px ,而我們的屏幕大小是 1440 * 900 px,那么 1440/900 = 1.6,920/960 = 2
因為 1.6 < 2 (當前屏幕寬高比小于設(shè)計稿寬高比)
所以我們需要縮放的比例是:屏幕寬度除以設(shè)計稿寬度 = 1440/1920 = 0.75
如何居中首先我們利用 transform:translate(-50%,-50%) ,將動畫的基點設(shè)為左上角
transform-origin:設(shè)置動畫的基點(中心點),默認點是元素的中心點
語法
transform-origin: x-axis y-axis z-axis;
然后利用transform:translate(-50%,-50%),將圖表沿 x,y 軸移動 50%

接下來利用絕對定位將圖表定位到中間位置
position: absolute;
left: 50%;
top: 50%;
復(fù)制代碼
偷懶方法-插件
v-scale-screen是使用 css 屬性 transform 實現(xiàn)縮放效果的一個大屏自適應(yīng)組件,通過 scale 進行等比例計算,達到等比例縮放的效果,同時也支持鋪滿全屏,寬度等比,高度等比,等自適應(yīng)方案,具體可查大屏自適應(yīng)終極解決方案
方案三:rem + vw wh
上效果

當屏幕的尺寸比例剛好是 16:9 時,頁面能剛好全屏展示,內(nèi)容占滿顯示器

當屏幕的尺寸比例小于 16:9 時,頁面上下留白,左右占滿并上下居中,顯示比例保持 16:9

當屏幕尺寸比例大于 16:9 時,頁面左右留白,上下占滿并居中,顯示比例保持 16:9

實現(xiàn)思路
關(guān)于 remrem(font size of the root element),是 css3 中新增的一個大小單位,即相對于根元素 font-size 值的大小。自適應(yīng)思路動態(tài)的計算出頁面的 fontsize 從而改變 rem 的大小。
拿 1920 * 1080 的標準屏幕大小為例,將屏幕分為 10份,先計算rem 的基準值:1920 / 10 = 192;把所有元素的長、寬、位置、字體大小等原來的 px 單位全部轉(zhuǎn)換成 rem; 網(wǎng)頁加載后,用 js 去計算當前瀏覽器的寬度,并設(shè)置 html 的 font-size 為 ( 當前瀏覽器窗口寬度 / 10) 。 這樣的話 10rem 就剛好等于瀏覽器窗口的寬度,也就可以保證 100% 寬度,等比例縮放設(shè)計稿的頁面了。
因此 rem + vm vh 方案要解決三件事
獲得 rem 的基準值; 頁面內(nèi)寫一段 js 代碼,動態(tài)的計算 html根元素的font-size;屏幕變化后,圖表自動調(diào)整和圖表字體、間距、位移等的自適應(yīng)。
實現(xiàn)方案
第一點:獲得 rem 的基準值
首先安裝 @njleonzhang/postcss-px-to-rem這個包
npm i @njleonzhang/postcss-px-to-rem -D
復(fù)制代碼
在項目根目錄新建 .postcssrc.js配置文件
module.exports = {
plugins: {
autoprefixer: {},
"@njleonzhang/postcss-px-to-rem": {
unitToConvert: 'px', // (String) 要轉(zhuǎn)換的單位,默認是 px。
widthOfDesignLayout: 1920, // (Number) 設(shè)計布局的寬度。對于pc儀表盤,一般是 1920.
unitPrecision: 3, // (Number) 允許 rem 單位增長到的十進制數(shù)字.
selectorBlackList: ['.ignore', '.hairlines'], // (Array) 要忽略并保留為 px 的選擇器.
minPixelValue: 1, // (Number) 設(shè)置要替換的最小像素值.
mediaQuery: false // (Boolean) 允許在媒體查詢中轉(zhuǎn)換 px.
}
}
}
復(fù)制代碼
配置完成后,頁面內(nèi)的 px 就會被轉(zhuǎn)換成 rem 了
第二點:動態(tài)的計算html根元素的font-size
在工具函數(shù)文件中新建一個 rem.js 文件,用于動態(tài)計算 font-size
(function init(screenRatioByDesign = 16 / 9) {
let docEle = document.documentElement
function setHtmlFontSize() {
var screenRatio = docEle.clientWidth / docEle.clientHeight;
var fontSize = (
screenRatio > screenRatioByDesign
? (screenRatioByDesign / screenRatio)
: 1
) * docEle.clientWidth / 10;
docEle.style.fontSize = fontSize.toFixed(3) + "px";
console.log(docEle.style.fontSize);
}
setHtmlFontSize()
window.addEventListener('resize', setHtmlFontSize)
})()
復(fù)制代碼
在入口文件 main.js 中引入 rem.js 文件
import './utils/rem.js';
復(fù)制代碼
至此,頁面就已經(jīng)可以實現(xiàn) 16:9 自適應(yīng)了。
第三點:屏幕變化,圖表自適應(yīng)屏幕變化后,圖表自動調(diào)整字體、間距、位移等,此處參考上面 vm vh 的實現(xiàn)方式即可,在此就不重復(fù)贅述了
參考資料
推薦一個echarts 的案列網(wǎng)站,需要什么直接圖表直接在上面去找,可以省去很多查 echarts 配置的時間全網(wǎng)echarts案例資源大總結(jié)和echarts的高效使用技巧(細節(jié)版) scale 方案參考: 數(shù)據(jù)大屏最簡單自適應(yīng)方案,無需適配rem單位 vm vh 方案參考: Vue+Echarts企業(yè)級大屏項目適配方案 rem 方案參考:數(shù)據(jù)大屏rem適配方案
作者:懶惰的智慧
鏈接:https://juejin.cn/post/7163932925955112996
我組建了一個氛圍特別好的 Node.js 社群,里面有很多 Node.js小伙伴,如果你對Node.js學習感興趣的話(后續(xù)有計劃也可以),我們可以一起進行Node.js相關(guān)的交流、學習、共建。下方加 考拉 好友回復(fù)「Node」即可。
“分享、點贊、在看” 支持一波??
