Place text in center of pie chart - Highcharts

后端 未结 7 634
-上瘾入骨i
-上瘾入骨i 2020-12-08 00:57

I would like to place a title in the center of a pie/donut chart in HighCharts.

I don\'t see anything in the chart options that would directly enable this, so I\'m t

7条回答
  •  离开以前
    2020-12-08 01:37

    You need to take into account the location of the chart, so if you use the 'left' and 'top' attributes, you can add on half the width of the plot and subtract half the width of your text bounding box. This would yield the exact center:

    text = chart.renderer.text("My Text").add();
    textBBox = text.getBBox();
    x = chart.plotLeft + (chart.plotWidth  * 0.5) - (textBBox.width  * 0.5);
    y = chart.plotTop  + (chart.plotHeight * 0.5) - (textBBox.height * 0.5);
    text.attr({x: x, y: y});
    

    Apparently the bounding box will be 0s unless you add it first.

    Correction:

    y = chart.plotTop  + (chart.plotHeight * 0.5) + (textBBox.height * 0.25);
    

    So, my original thought, and this seemed fine, was that the text would be aligned by the upper left, however it is done by the bottom left instead. Thus, instead of subtracting half the height, we actually need to add it. What confuses me, and something I don't understand yet, is that to get the center you add only 25% of the height rather then 50%. Note: This does not appear to work on IE 7 or 8.

    MAJOR UPDATE

    http://jsfiddle.net/NVX3S/2/

    <- Centered text that works in all browers

    What this new update does is it adds a new element using jquery after the chart is done. This works in all browers that I have tested (including IE7, 8, 9, Firefox and Chrome).

    var textX = chart.plotLeft + (chart.plotWidth  * 0.5);
    var textY = chart.plotTop  + (chart.plotHeight * 0.5);
    
    // The width and height need to be calculated properly, so I made it a span.
    var span = '';
    span += 'Upper
    '; span += 'Lower'; span += '
    '; $("#addText").append(span); span = $('#pieChartInfoText'); span.css('left', textX + (span.width() * -0.5)); span.css('top', textY + (span.height() * -0.5));

提交回复
热议问题