简介:echarts图标文字自适应
本文以vue2为例,vue3自己改下写法即可
echarts自带的resize方法只能让图表主体实现自适应,而图例、文字等元素都无法自适应,导致页面缩放时内容错乱,网上看了很多文章尝试了很多办法都不能生效,经过多次尝试得出实用方案
一、第一步
需要在页面添加计算字体大小的函数
methods: {
fontSize(res) {
let clientWidth =
window.innerWidth ||
document.documentElement.clientWidth ||
document.body.clientWidth;
if (!clientWidth) return;
let fontSize = 100 * (clientWidth / 1920);
return res * fontSize;
},
},
二、第二步
修改echart配置项,由于echarts不能接收rem作为单位,所以需要在设置字体大小的选项中使用第一步的函数计算,以下是一个环形图的配置选项例子
option: {
tooltip: {
trigger: "item"
},
legend: {
top: "85%",
left: "center",
textStyle: {
color: "#fff",
fontSize: this.fontSize(0.13)//设计稿是13px
},
itemWidth: this.fontSize(0.25),//设计稿是25px
itemHeight: this.fontSize(0.14)
},
series: [
{
name: "卫星在线数量",
type: "pie",
radius: ["45%", "60%"],
avoidLabelOverlap: false,
label: {
show: false,
position: "center"
},
labelLine: {
show: false
},
data: [
{ value: 50, name: "在线", itemStyle: { color: "#ff4500" } },
{ value: 200, name: "离线", itemStyle: { color: "#1e90ff" } }
]
}
]
}
三、第三步
此时发现页面改变时并未生效,那是因为fontSize()函数只有挂载时被执行了一次,后面无论页面如何变化echarts都不会重新设置option,所以我们需要在监听函数里修改option的值然后重新让echarts渲染出来
添加监听函数
window.addEventListener("resize", this.chartsResize);
监听函数示例
chartsResize() {
myChart.resize();
this.$set(this.option.legend.textStyle, "fontSize", this.fontSize(0.13));
this.$set(this.option.legend, "itemWidth", this.fontSize(0.25));
this.$set(this.option.legend, "itemHeight", this.fontSize(0.14));
myChart.setOption(this.option, true);
}
注意此处一定要手动修改配置项里的数据,千万不能省略这一步!否则配置无效,原因是渲染时option中使用fontSize函数的选项值不会自动计算,而是只最开始计算一次,导致echarts的option的选项没有改变,使用监听函数后实时计算每个配置项的值并让echarts重新渲染即可