實(shí)現(xiàn) ECharts 圖表自適應(yīng)

數(shù)據(jù)可視化的需求越來越多,圖表自動(dòng)生成技術(shù)也日漸成熟

ECharts

ECharts 的功能十分強(qiáng)大,可以生成多種形式的圖表,配置項(xiàng)十分靈活,可以根據(jù)實(shí)際需求自由定制
官方文檔: https://www.echartsjs.com/examples/

但是ECharts繪制圖表時(shí)無法獲取到clientWidth,而 parseInt(stl.width, 10)) 將width: 100%;轉(zhuǎn)為100,所以計(jì)算出的圖表寬度為100px

所以設(shè)置width:100%對(duì)echarts是不起作用的

解決方法

思路:mounted時(shí)獲取window對(duì)象的寬高,結(jié)合實(shí)際需要對(duì)window的寬高進(jìn)行計(jì)算,然后將寬高經(jīng)過計(jì)算賦給需要渲染圖表的DOM節(jié)點(diǎn),這樣一來echarts節(jié)點(diǎn)渲染之前就獲得了具體的寬高,大小就可以適應(yīng)不同的屏幕了。

具體實(shí)現(xiàn)函數(shù)如下:

<template>
 <div id="main" ref="mychart"></div>
</template>
<script>
export default {
 mounted: function () {
            this.loadBugChart();
 },
 methods: {
  loadBugChart() {
                var domBugChart= this.$refs.mychart; //獲取DOM節(jié)點(diǎn)
                //自適應(yīng)寬高
                var bugChartContainer = function () {
                    if (domBugChart) {
                        domBugChart.style.width = 66+"vw";
                        domBugChart.style.height = 70+"vh";
                        // 相當(dāng)于
                        // domBugChart.style.width = window.innerWidth * 0.66 + 'px';
                        // domBugChart.style.height = window.innerHeight * 0.7 + 'px';
                    }

                };
                bugChartContainer();
                var bugChart = echarts.init(domBugChart);
                let option = {...};
                bugChart.setOption(option);
            }
     }
}
</script>

這樣做有一個(gè)缺點(diǎn),頁面大小改變之后需要刷新,刷新之后圖表自適應(yīng),不過實(shí)際使用中頁面適配屏幕后大小改變的應(yīng)用場(chǎng)景不多。

進(jìn)階版

echarts官方提供了獲取圖表寬高的API函數(shù) getWidth() getHeight(),可以對(duì)其進(jìn)行操作,在自適應(yīng)的前提下,設(shè)置圖表最小寬高

loadSheetChart() {
      var domSheetChart = this.$refs.sheetChart;
      this.sheetChart = echarts.init(domSheetChart);
      let width =
        this.sheetChart.getWidth() < 250 ? 250 : this.sheetChart.getWidth();
      let height = this.sheetChart.getHeight();
    },

使用官方API resize ()

    barChartLoad() {
      const barChart = echarts.init(document.getElementById('barChart'));
      barChart.setOption(this.barChartOption);
      window.onresize = function() {
        barChart.resize();
      };
    },

推薦,使用起來方便簡潔

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容