【问题标题】:Increasing font size in C3 charts without cutting off the text在不截断文本的情况下增加 C3 图表中的字体大小
【发布时间】:2016-01-18 05:58:09
【问题描述】:

我尝试了不同的 CSS 技术来更改 C3 图表中文本的字体大小。但是当我使用 CSS 时,文本会被截断超过特定的字体大小(例如 14 像素)。我正在使用带有 y 轴标签的水平条形图,并在每个条的末尾显示数据(类似这样的东西 - http://c3js.org/samples/axes_rotated.html )。有没有办法通过 C3 API 自定义字体大小?如果没有,处理此类情况的最佳方法是什么?

【问题讨论】:

    标签: javascript css d3.js c3.js


    【解决方案1】:

    请查找代码和fiddle

       d3.selectAll('.c3-text')
            .each(function(d){
            var self = d3.select(this),
                width = +d3.select('.c3-zoom-rect').attr('width');
            if (+self.attr('x') + self.node().getComputedTextLength() > width){
                self.attr('text-anchor', 'end');
              self.attr('dx', '-5');
            }
        });
    

    如果您遇到折线图的轴字体大小切割问题,只需添加:

    c3.generate({
    ...
    padding: {
      left: 500
    },
    ...
    });
    

    要设置动态值,请尝试使用一个小 jQuery 插件来获取文本字符串的长度:

    $.fn.textWidth = function(text, font) {
      if (!$.fn.textWidth.fakeEl) $.fn.textWidth.fakeEl = $('<span>').hide().appendTo(document.body);
      $.fn.textWidth.fakeEl.text(text || this.val() || this.text()).css('font', font || this.css('font'));
      return $.fn.textWidth.fakeEl.width();
    };
    
    var longest_text_width = 0;
    chartData[0].forEach(function(data) {
      var w = $.fn.textWidth(data, '13px Clear Sans');
        if (w > longest_text_width) {
          longest_text_width = w;
        }
    });
    
    var chart = c3.generate({
    
      ...
    
      padding: {
        left: longest_text_width + 10 // add 10px for some spacing
      },
    
      ...
    
    });
    

    【讨论】:

      猜你喜欢
      • 2014-02-28
      • 2016-03-24
      • 2017-08-31
      • 1970-01-01
      • 2013-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-02
      相关资源
      最近更新 更多