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

ECharts中嵌套rich样式实现文本居中失效问题求助

ECharts 富文本嵌套样式无法实现文本居中的解决方案

你尝试通过嵌套ECharts的rich样式,让文本在bg背景区块内居中,但嵌套写法无法生效;不嵌套时文本能正常显示,却达不到居中效果。

问题原因

ECharts的rich样式嵌套时,内层的center样式无法正确作用于外层bg区块的文本对齐。实际上不需要额外嵌套样式,直接在bg的rich配置里添加文本对齐属性即可实现需求。

解决方案

修改rich配置中的bg样式,添加align: 'center'属性,同时移除无效的嵌套写法,直接在bg区块中放入文本即可。

修改后的 formatter 代码

formatter: function(params) {
  const nome = params.name;
  const valor = params.value;
        
  return ["{bg|" + nome + "}", "{c|Content}"].join("\n");
}

修改后的 rich 配置

rich: {
  bg: {
    backgroundColor: "#020202",
    color: "#f2f2f2",
    height: 20,
    width: "100%",
    borderRadius: [3, 3, 0, 0],
    padding: [0, 10, 0, 10],
    align: 'center' // 新增文本居中属性
  },
  c: {
    color: "#020202"
  }
}

完整修改代码

JavaScript 部分

document.addEventListener("DOMContentLoaded", function() {
  const myChartUse = echarts.init(document.getElementById("myChart"));
  option = {
    series: [{
      type: "pie",
      radius: ["70%", "55%"],
      padAngle: 5,
      itemStyle: {
        normal: {
          borderRadius: 5
        },
        emphasis: {
          color: "#40bcac"
        }
      },
      label: {
        borderWidth: 2,
        width: 120,
        padding: 2,
        borderColor: "#020202",
        formatter: function(params) {
          const nome = params.name;
          const valor = params.value;
          return ["{bg|" + nome + "}", "{c|Content}"].join("\n");
        },
        rich: {
          bg: {
            backgroundColor: "#020202",
            color: "#f2f2f2",
            height: 20,
            width: "100%",
            borderRadius: [3, 3, 0, 0],
            padding: [0, 10, 0, 10],
            align: 'center'
          },
          c: {
            color: "#020202"
          }
        }
      },
      data: [
        { name: "Value 1", value: 78 },
        { name: "Value2", value: 22 }
      ]
    }]
  }
  myChartUse.setOption(option);
})

HTML 部分

<head>
<script src="https://cdn.jsdelivr.net/npm/echarts@5.5.0/dist/echarts.min.js"></script>
</head>
<div id="myChart" style="height: 450px; width: 600px;"></div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 08:36:01