Echarts文字大小自适应,案例详解 您所在的位置:网站首页 echarts怎么用css调整页面宽度 Echarts文字大小自适应,案例详解

Echarts文字大小自适应,案例详解

2024-06-17 08:09| 来源: 网络整理| 查看: 265

用echarts做可视化大屏的时候,图表大小可以自适应,但是图表里面文字的大小不能自适应。有一种解决方法就是采用rem为单位,根据屏幕的宽度调整html的font-size。

在这里插入图片描述

先定义一个函数fontSize(),用来获取屏幕宽度并计算比例,在需要设置字体的地方调用这个函数即可。

getEcharts(){ //获取屏幕宽度并计算比例 function fontSize(res){ let clientWidth = window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth; if (!clientWidth) return; let fontSize = 100 * (clientWidth / 1920); return res*fontSize; } var dom = document.getElementById('qualres'); var myChart = echarts.init(dom); var option = { title: { text: '近七天内访问量和下载量', subtext: '访问次数(次)', itemGap: 10, textStyle: { //调用fontSize()方法,此时fontSize为18px fontSize: fontSize(0.18) }, subtextStyle: { color: 'gray', fontSize: fontSize(0.12) } }, tooltip: { trigger: 'axis', }, legend: { data: ['访问量', '下载量'], right: 20, itemGap: 30, icon: 'circle', textStyle: { fontSize: fontSize(0.14) } }, grid: { top: '60px', left: '1%', right: '1%', bottom: '0', containLabel: true }, xAxis: { type: 'category', boundaryGap: false, data: ['12.01', '12.02', '12.03', '12.04', '12.05', '12.06', '12.07'], axisTick:{ show: false, }, axisLine: { show: false }, axisLabel: { color: '#666666', margin: 10, fontSize: fontSize(0.12) }, boundaryGap: true, }, yAxis: { type: 'value', axisTick:{ show: false }, axisLine: { show: false }, axisLabel: { color: '#666666', margin: 10, fontSize: fontSize(0.12) }, interval:10, min:0, max:40, }, series: [{ name: '访问量', type: 'line', symbol: 'circle', smooth: true, data: [19, 23.5, 32, 30, 26, 32, 27], color: 'rgb(251,168,46)', },{ name: '下载量', type: 'line', symbol: 'circle', smooth: true, data: [11, 10, 9, 15.5, 18, 17, 13], color: 'rgb(30,135,240)', }] } //视口调整后重新渲染echart图表 window.onresize = function () { myChart.resize() }; myChart.setOption(option); },

echart图表本身提供了一个resize()函数,当浏览器发生resize事件时,让其触发echart的resize()函数,可以重绘canvas,实现图表自适应。

此时,字体的大小并不能随着图表自适应(必须刷新页面),需要设置监听事件addEventListener,在浏览器窗口发生变化时重新执行图表方法:

mounted(){ this.getEcharts(); window.addEventListener('resize',()=>{ this.getEcharts(); }) },


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有