/** * @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; };
// 计算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, };