echarts 字体自适应
时间: 2023-07-08 08:56:18 浏览: 42
ECharts 提供了文本样式配置项 textStyle,可以通过设置 fontSize 属性来控制文本字体大小。而要实现字体自适应,可以通过 ECharts 提供的 API 得到容器的宽度,然后根据容器的宽度计算出合适的字体大小,再设置到 textStyle 中的 fontSize 属性中。
以下是一个示例代码:
```javascript
var myChart = echarts.init(document.getElementById('myChart'));
var option = {
// 其他配置项...
textStyle: {
fontSize: 12 // 初始字体大小
},
series: [{
// 其他配置项...
label: {
show: true,
formatter: '{b}',
textStyle: {
fontSize: 12 // 初始字体大小
}
},
data: [{
// 其他配置项...
label: {
show: true,
formatter: '{b}',
textStyle: {
fontSize: 12 // 初始字体大小
}
}
}]
}]
};
// 计算合适的字体大小
function calculateFontSize() {
var width = myChart.getWidth(); // 获取容器宽度
var fontSize = Math.floor(width / 30); // 计算字体大小
// 设置字体大小
myChart.setOption({
textStyle: {
fontSize: fontSize
},
series: [{
label: {
textStyle: {
fontSize: fontSize
}
},
data: [{
label: {
textStyle: {
fontSize: fontSize
}
}
}]
}]
});
}
// 初始化时计算一次字体大小
calculateFontSize();
// 窗口大小发生变化时重新计算字体大小
window.onresize = function() {
calculateFontSize();
};
```
在上面的代码中,我们首先设置初始的字体大小为 12px,然后通过 getWidth() 方法获取容器的宽度,根据容器的宽度计算出合适的字体大小,再将字体大小设置到 textStyle 中的 fontSize 属性中。最后,在窗口大小发生变化时,重新计算字体大小。