Echarts 標簽中文本內容太長的時候怎么辦 ?
關於這個問題搜索一下,有很多解決方案。無非就是 省略(間隔顯示)、旋轉文字方向、豎排展示
前面兩種解決方案,就是echarts暴露的:
{
axisLabel: {
interval: 0,//如果設置為 1,表示『隔一個標簽顯示一個標簽』,如果值為 2,表示隔兩個標簽顯示一個標簽,以此類推。
rotate: '45',// 刻度標簽旋轉的角度,在類目軸的類目標簽顯示不下的時候可以通過旋轉防止標簽之間重疊。
},
};
用法看官方文檔:
-
interval: https://echarts.apache.org/zh/option.html#xAxis.axisLabel.interval
-
rotate: https://echarts.apache.org/zh/option.html#xAxis.axisLabel.rotate
網上有關的設置也看了下,幾乎大同小異,比如:
-
Echarts x軸文本內容太長的幾種解決方案 https://www.jianshu.com/p/b452cbe9be0e
-
Echarts-axislabel文字過長導致顯示不全或重疊 https://www.cnblogs.com/hwaggLee/p/4762467.html
如何更加標簽文字的總長度自動采取調整策略
對於固定模式的圖標,我們直接設置 豎排展示或者旋轉就可了。但是對於圖表類平台,如何控制 X軸文字自適應顯示呢
這就需要我們去計算 x軸標簽文字的長度,然后去匹配圖表寬度,然后才去旋轉策略去顯示
如何計算字符串在瀏覽器中顯示的寬度
這個有兩種方法,一個是直接計算字符串,第二個是canvas里面計算
通過文本計算字符串的寬度
/**
* @description 計算字符串在瀏覽器中顯示的寬度
* @author andyzhou
* @create andyzhou
* @update 1/27/21 by andyzhou
* @param text {string|number}
* @param fontSize {number}
* @return {number}
*/
export default function computedTextWidth(text, fontSize = 14) {
let span = document.getElementById('computedTextWidth');
if (!span) {
span = document.createElement('span');
span.id = 'computedTextWidth';
span.style.cssText = 'visibility:hidden;position: absolute;left: -999em;top:-999em;';
document.body.appendChild(span);
}
span.style.fontSize = `${fontSize}px`;
span.innerHTML = text;
return span.offsetWidth;
};
這個方法可以共用,我就是直接采用這個
canvas里面計算文本寬度
在canvas繪圖環境中,measureText()方法可以度量字體的寬度。measureText()方法返回了一個包含width屬性的TextMetrics對象,后期我們會使用這個方法實現文本編輯器。
/**
* @description 計算字符串在瀏覽器中顯示的寬度
* @author andyzhou
* @create andyzhou
* @update 1/27/21 by andyzhou
* @param text {string|number}
* @param fontSize {number}
* @return {number}
*/
export default function computedTextWidth2(text, fontSize = 14) {
let canvas = document.getElementById('computedTextWidth');
if (!canvas) {
canvas = document.createElement('canvas');
canvas.id = 'computedTextWidth';
canvas.style.cssText = 'visibility:hidden;position: absolute;left: -999em;top:-999em;';
document.body.appendChild(canvas);
}
const context = canvas.getContext('2d');
context.font = `${fontSize}px`;
context.fillText(text, 0, 0);
return context.measureText(text).width;
};
推薦采用這個函數
vue組件里面 echart坐標軸自適應文本
// 計算x周文本總寬度
const textWidth = categoryData.reduce((value, current) => value + computedTextWidth(current), 0);
// 計算組件容器寬度
const width = this.$parent.$el.clientWidth;
const rotate = width - 50 > textWidth ? 0 : 40;
this.options.xAxis = {
type: 'category',
axisLabel: {
interval: 0,
rotate,
},
axisTick: { show: false },
data: categoryData,
};
其他調整,原理和這個差不都,就不贅述了
轉載本站文章《echarts圖表X軸文字過長解決解決方案:根據文字長度自動旋轉》,
請注明出處:https://www.zhoulujun.cn/html/webfront/visualization/charts/8611.html通過計算X軸文章渲染的總體寬度與圖表容器的寬度,然后自動去調整x軸的顯示方案,是才去旋轉還是 換行。文字可以正常顯示,不做調整。只有橫排顯示空間不夠時,才做調整。
