Echarts 5 瞎入门指南 - 2

273 阅读1分钟

在我们日常开发大屏端当中经常需要适配各种尺寸, 例如3840 / 1920 / 1080 等等, 我们盒模型可以用rem / vw等适配, 但是Echarts内部目前好像只支持 px 和 百分比, 这就给适配带来了难题, 尤其字体适配,如标题和legend等文字,目前坤坤只能想到两种方案

demo

 <template>
    <div ref="chart" class="chart"></div>
</template>

<script>
    import * as echarts from 'echarts'  // 版本 >= 5.0
    let myChart = null,
        option = {
            title : {
                text: 'Echarts文字适配',
                textStyle: {
                    color: '#fff',
                    fontSize: 16   //默认单位px
                },
                subtext: '二级标题',
                subtextStyle: {
                    fontSize: 12
                }
            }
        };
    
    ~function() {
        myChart = echarts.init(this.$refs.chart)  //实际情况需要等dom加载完
        myChart.setOption(option)
    }()
</script>

方案一: 三目运算

const win = window.innerWidth > 1440,
    option = {
        title : {
            text: 'Echarts文字适配',
            textStyle: {
                color: '#fff',
                fontSize: win ? 24 : 16 
            },
            subtext: '二级标题',
            subtextStyle: {
                fontSize: win ? 16 : 12
            }
        }
    }

方案二: Media Query

现在支持三个属性 width、height、aspectRatio(长宽比)
 option = {
        media: [
            {
                query: {
                    maxWidth: 1920,  // <=1920px
                    //maxAspectRatio: 2  //长度比 < 2
                },
                option: {
                    legend: {
                        textStyle: {
                            fontSize: 24
                        }
                    }
                }
            },
            {
                query: { minWidth: 1921 },   // >=1921px
                option: {
                    legend: {
                        textStyle: {
                            fontSize: 16
                        }
                    }
                }
            },
            //当media 中有某项不写 query,则表示『默认值』,即所有规则都不满足时,采纳这个option
           {
               //baseOption
                option: {
                    legend: {
                        textStyle: {
                            fontSize: 12
                        }
                    },
                    title: {},
                    xAxis: {},
                    series: []
                }
            } 
        ]
    }

注意: 当有多个query同时满足时, 后面的覆盖前面的

最后的轻语

    第一篇和第二篇是孪生兄弟一起发布的, 所以这篇比较短,影子是谁不用我再说了吧