달력

5

« 2024/5 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

'doughnut inside'에 해당되는 글 1

  1. 2017.12.12 Chart.js에서 도넛/반도넛 차트 가운데에 숫자 적는 법
반응형

지난번에 말한 대로 Chart.plugins.register를 이용해서 chart.js의 반도넛 차트 안에 숫자를 적을 수 있다.

방법은 다음과 같은 소스를 도넛 차트를 그리는 js에 넣고 도넛 차트 옵션에 elements.center를 만들면 된다.

(이전 포스팅 참조 : chart.js에서 반도넛 그래프 그리는 법)

Chart.plugins.register({
  beforeDraw: function (chart) {
	  if (chart.config.options.elements.center) {
	      //Get ctx from string
	      var ctx = chart.chart.ctx;

	      //Get options from the center object in options
	      var centerConfig = chart.config.options.elements.center;
	      var fontSize = centerConfig.fontSize || '50';
	      var fontStyle = centerConfig.fontStyle || 'Arial';
	      var txt = centerConfig.text;
	      var color = centerConfig.color || '#000';
	      var sidePadding = centerConfig.sidePadding || 20;
	      var sidePaddingCalculated = (sidePadding/100) * (chart.innerRadius * 2)
	      //Start with a base font of 30px
	      ctx.font = fontSize + "px " + fontStyle;

	      //Get the width of the string and also the width of the element minus 10 to give it 5px side padding
	      var stringWidth = ctx.measureText(txt).width;
	      var elementWidth = (chart.innerRadius * 2) - sidePaddingCalculated;

	      // Find out how much the font can grow in width.
	      var widthRatio = elementWidth / stringWidth;
	      var newFontSize = Math.floor(30 * widthRatio);
	      var elementHeight = (chart.innerRadius * 0.7);

	      // Pick a new font size so it will not be larger than the height of label.
	      var fontSizeToUse = Math.min(newFontSize, elementHeight);

	      //Set font settings to draw it correctly.
	      ctx.textAlign = 'center';
	      ctx.textBaseline = 'middle';
	      var centerX = ((chart.chartArea.left + chart.chartArea.right) / 2);
	      var centerY = ((chart.chartArea.top + chart.chartArea.bottom) / 2);

	      //반도넛일 경우
	      if (chart.config.options.rotation === Math.PI && chart.config.options.circumference === Math.PI) {
	        centerY = ((chart.chartArea.top + chart.chartArea.bottom) / 1.3);
	      }
	      ctx.font = fontSizeToUse+"px " + fontStyle;
	      ctx.fillStyle = color;

	      //Draw text in center
	      ctx.fillText(txt, centerX, centerY);
	    }
  }
});

 

 

만약 숫자가 너무 올라가있거나 내려가 있으면 38번 줄의 수식을 변경해주면 된다.

 

출처 : https://stackoverflow.com/questions/20966817/how-to-add-text-inside-the-doughnut-chart-using-chart-js

반응형
:
Posted by 리샤씨


반응형
반응형