You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ECharts v5中实现文本超出矩形框时显示省略号

ECharts v5 实现文本超出矩形框显示省略号方案

在ECharts v5的自定义系列中,想要实现文本超出矩形框时自动显示省略号,但官方文档中没有直接对应的API可用。当前用于添加文本的代码如下:

(
    rectShape && {
      type: "rect",
      transition: ["shape"],
      shape: rectShape,
      style: api.style({
        text: api.value(3),
        textFill: "blue",
        textAlign: "right"
      })
    }
);

实现方案

ECharts自定义系列的文本渲染没有内置省略号逻辑,需要手动处理文本截断,具体步骤如下:

  1. 计算文本与矩形宽度
    通过ZRender创建临时文本元素,获取文本实际渲染宽度;同时从rectShape中提取矩形的可用宽度。

  2. 文本截断与省略号添加
    循环截取文本内容,直到文本宽度小于等于矩形可用宽度(需预留省略号的宽度),最后给截断后的文本追加省略号。

  3. 修改代码实现
    调整原代码中的文本赋值逻辑,替换为处理后的截断文本:

// 辅助函数:计算文本渲染宽度
function getTextWidth(text, style) {
  const zr = api.getZr();
  const textEl = zr.createElement('text', {
    style: {
      ...style,
      text: text
    }
  });
  const { width } = textEl.getBoundingRect();
  zr.remove(textEl);
  return width;
}

// 处理文本截断逻辑
const originalText = api.value(3);
const textStyle = {
  textFill: "blue",
  textAlign: "right"
};
const rectWidth = rectShape.width;
// 预计算省略号的宽度,可根据字体参数调整
const ellipsisWidth = getTextWidth('...', textStyle);
let truncatedText = originalText;

// 循环截断直到文本宽度符合限制
while (getTextWidth(truncatedText, textStyle) > rectWidth - ellipsisWidth && truncatedText.length > 0) {
  truncatedText = truncatedText.slice(0, -1);
}

// 仅在文本被截断时添加省略号
if (truncatedText !== originalText) {
  truncatedText += '...';
}

// 返回最终图形配置
rectShape && {
  type: "rect",
  transition: ["shape"],
  shape: rectShape,
  style: api.style({
    text: truncatedText,
    ...textStyle
  })
};

注意事项

  • 临时文本元素的创建会带来一定性能开销,若需渲染大量数据,建议缓存已计算过的文本宽度
  • 省略号的宽度需根据实际字体、字号调整,避免出现省略号超出矩形的情况
  • 该逻辑适用于left/center/right等任意文本对齐方式,只需保证文本总宽度不超过矩形宽度即可

内容的提问来源于stack exchange,提问作者Pytan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 07:17:16