echarts官网中有resize这个函数帮助我们实现图表的自适应,我们只需要监听页面窗口的变化,然后使用resize这个函数就可以了。
这个时候,图表会自动变化,但是有时候,除了图表,图表中的其他元素也需要根据自动变化,如图例中的字体,图中的字体什么的,这个时候,使用resize图表中的字体并不会相应地进行变化,幸运的是,网上有解决方案,echarts大屏字体自适应的方法步骤
通过这个,我们可以让图表在窗口变化时,不仅图表本身有变化,图表中的字体也会有变化,相关的代码如下
this.myChart = echarts.init(document.getElementById('main'));
this.setOptions();
window.onresize = () => {
this.setOptions();
this.myChart.resize();
};
getOptions = () => {
const options = {
tooltip: {
trigger: 'item',
formatter: '{c}',
},
color: ['#F04864', '#1890FF', '#FACC14', '#4DCB73'],
legend: {
orient: 'vertical',
top: 'middle',
left: '45%',
x: 'left',
icon: 'circle',
itemGap: 15,
itemWidth: this.fontSize(0.1),
itemHeight: this.fontSize(0.1),
formatter(name) {
return `{a|${name}}`;
},
textStyle: {
// rich放在textStyle里面
rich: {
a: {
// width: 50,
fontSize: this.fontSize(0.15),
padding: 0,
color: '#fff',
},
b: {
color: '#fff',
// width: 50,
fontSize: this.fontSize(0.15),
padding: 0,
},
c: {
color: '#fff',
},
},
},
data: ['测试1','测试1','测试1','测试1',],
},
title: {
text: stat.total,
subtext: formatMessage({ id: '总条数' }),
left: '24%',
top: '40%',
textAlign: 'center',
textStyle: {
color: '#fff',
fontSize: this.fontSize(0.23),
},
subtextStyle: {
color: '#fff',
fontSize: this.fontSize(0.15),
},
},
series: [
{
emphasis: {
show: false,
},
type: 'pie',
center: ['25%', '50%'],
radius: ['40%', '55%'],
avoidLabelOverlap: false,
label: {
normal: {
position: 'inner',
show: false,
},
},
labelLine: {
normal: {
show: false,
},
},
data:[
{
name:'测试1',
value:34
},
{
name:'测试2',
value:345
},
{
name:'测试4',
value:36
},
{
name:'测试3',
value:34
}
],
},
],
};
return options;
};
setOptions = () => {
const options = this.getOptions();
// 绘制图表
this.myChart.setOption(options);
};
fontSize = res => {
const clientWidth =
window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
if (!clientWidth) return '16px';
const fontSize = 100 * (clientWidth / 1920);
return res * fontSize;
};