首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在echarts中自动缩放字体大小?

如何在echarts中自动缩放字体大小?
EN

Stack Overflow用户
提问于 2020-01-02 15:03:12
回答 1查看 3.6K关注 0票数 0

我真的没有问题,只是想在这里分享我的知识。

这是一个关于如何在echarts.js中根据div大小自动缩放字体大小的知识分享。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-01-02 15:03:12

代码语言:javascript
运行
复制
let myChart = echarts.init(document.getElementById('myChart'));

function autoFontSize() {
  let width = document.getElementById('myChart').offsetWidth;
  let newFontSize = Math.round(width / 11);
  console.log(`Current width : ${width}, Updating Fontsize to ${newFontSize}`);
  return newFontSize;
};

const fruits = [{
    value: 100,
    name: "Apple(s)"
  },
  {
    value: 200,
    name: "Banana(s)"
  }
];

const sum = fruits.reduce(function(prev, current) {
  return prev + current.value
}, 0);



let myChartOption = {
  grid: {
    left: 0,
    top: 0,
    right: 0,
    bottom: 0
  },
  tooltip: {
    trigger: 'item',
    textStyle: {
      fontSize: '15',
    },
    formatter: 'You have {c} {b}'
  },
  legend: {
    orient: 'vertical',
    x: 'right',
    y: 'bottom',
    padding: 0,
    itemGap: 0,
    textStyle: {
      fontSize: '15',
    },
    formatter: function(name) {
      var targetValue = 0;
      fruits.forEach(function(c) {
        if (c.name == name) {
          targetValue = c.value;
        }
      });
      return targetValue + ' ' + name;
    }
  },
  series: [{
    name: 'fruits',
    type: 'pie',
    center: ['50%', '40%'],
    radius: ['50%', '60%'],
    avoidLabelOverlap: false,
    label: {
      position: 'center',
      textStyle: {
        fontSize: autoFontSize(),
        fontWeight: 'bold'
      },
      color: 'black',
      formatter: '' + sum,
    },
    labelLine: {
      normal: {
        show: false
      }
    },
    data: fruits,
    itemStyle: {
      emphasis: {
        shadowBlur: 10,
        shadowOffsetX: 0,
        shadowColor: 'rgba(0, 0, 0, 0.5)'
      }
    }
  }]
};


myChart.setOption(myChartOption);


$(window).on('resize', function() {
  if (myChart != null && myChart != undefined) {
    myChart.resize({
      width: 'auto',
      height: 'auto'
    });
    myChart.setOption({
      series: {
        label: {
          textStyle: {
            fontSize: autoFontSize()
          }
        }
      }
    })
  }
});
代码语言:javascript
运行
复制
#myChart {
  width: 100%;
  min-height: 330px;
  margin: 0 auto;
}
代码语言:javascript
运行
复制
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/4.6.0/echarts.min.js"></script>
<div id="myChart"></div>

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59559511

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档