2013-05-16 7 views
39

멋진 플러그인 Chart.js을 사용하고 있으며 각 백분율 내에서 표시 방법을 찾는 중입니다. 그래서 나는 그것을 인터넷 검색, 나는이 풀을 발견 : https://github.com/nnnick/Chart.js/pull/35Chart.js 캔버스 플러그인에 라벨을 추가하는 방법은 무엇입니까?

나는 그것을 테스트하는 간단한 바이올린을했다,하지만 작동하지 않습니다 : http://jsfiddle.net/marianico2/7ktug/1/

이는 내용이다 :

HTML

<canvas id="canvas" height="450" width="450"></canvas> 

JS

$(document).ready(function() { 
    var pieData = [{ 
     value: 30, 
     color: "#F38630", 
     label: 'HELLO', 
     labelColor: 'black', 
     labelFontSize: '16' 
    }, { 
     value: 50, 
     color: "#E0E4CC" 
    }, { 
     value: 100, 
     color: "#69D2E7" 
    }]; 

    var myPie = new Chart(document.getElementById("canvas").getContext("2d")).Pie(pieData, { 
     labelAlign: 'center' 
    }); 
}); 

은 내가 documentation이에 대한 정보가없는 두려워.

또한 각 부분에 대한 레이블을 표시하는 방법을 알고 싶지만 차트 외부에 있습니다. 선으로 연결됩니다. highcharts.js의 차트도 마찬가지입니다.

그런데, 내가 위에서 말한 옵션을 포함하는 html5 차트 대안을 권해 주시면 기쁠 것입니다. flot 플러그인에 대해 들었지만 애니메이션을 지원하지 않을까합니다 ...

자세한 정보가 필요하면 알려 주시면 해당 게시물을 편집하겠습니다.

+3

에 레이블로 백분율을 표시하려고했다. – Jack

+3

@ 잭 올바른지,이 파일을 사용해야합니다 : https://github.com/Regaddi/Chart.js/blob/9fe98b61c5c059bcf347508ac724d38f6eb83764/Chart.min.js –

+6

작업 jsfiddle 참조하십시오 : http://jsfiddle.net/7ktug/2/ –

답변

31

두 곳에서 코드를 추가해야합니다. 예를 들어, 도넛을 가져 가라. 먼저 기본값으로 레이블 정보를 추가 (원래 Chart.js 코드를보고이 비교) :

chart.Doughnut.defaults = { 
     segmentShowStroke : true, 
     segmentStrokeColor : "#fff", 
     segmentStrokeWidth : 2, 
     percentageInnerCutout : 50, 
     animation : true, 
     animationSteps : 100, 
     animationEasing : "easeOutBounce", 
     animateRotate : true, 
     animateScale : false, 
     onAnimationComplete : null, 
     labelFontFamily : "Arial", 
     labelFontStyle : "normal", 
     labelFontSize : 24, 
     labelFontColor : "#666" 
    }; 

그런 다음 도넛이 그려지는 곳으로 가서 네 ctx 라인을 추가합니다. 당신은 X, Y 좌표 텍스트를 작성하는 것을 사용할 수 있도록

animationLoop(config,null,drawPieSegments,ctx); 

    function drawPieSegments (animationDecimal){ 
     ctx.font = config.labelFontStyle + " " + config.labelFontSize+"px " + config.labelFontFamily; 
     ctx.fillStyle = 'black'; 
     ctx.textBaseline = 'middle'; 
     ctx.fillText(data[0].value + "%", width/2 - 20, width/2, 200); 

ctx.fillText 호출은, 캔버스에 텍스트를 넣어 것입니다. 이 방법으로 기본 레이블을 작성할 수 있어야합니다. 여기에 수리를 할 수있는 jsfiddle입니다 : 당신은 애호가 뭔가를해야 할 경우, 누군가가 Charts.js의 버전을 포크

http://jsfiddle.net/nCFGL/ (상기 코드에 대한 jsfiddle의 자바 스크립트 부분에 라인 281에서 모양과 772) 및 툴팁이 추가되었습니다. 여기에 https://github.com/nnnick/Chart.js/pull/35 토론이 있으며, 토론 내에서 갈래의 버전에 대한 링크를 찾을 수 있습니다.

+2

이것은 나를 도왔습니다. 네가 무슨 말을하고 있었는지 알아내는 데는 시간이 걸렸지 만 나는 그걸 관리했다. 다른 사용자를 위해이 코드는 758 행의 원래 Chart.js에 있습니다. 사용자가 제공 한 피들 예제로 수정해야합니다. 번호를 써서 원하는 방식으로 중앙에 올릴 수 있습니다. 감사합니다 – CodeGodie

+0

Chart.js 코드가 조금 변경되었습니다 같아요.이 줄을 변경하고 텍스트에 백분율 char 추가하여 어쨌든 해결 : ctx.fillText (this.text + "%", tooltipX + tooltipWidth/2 , tooltipY + tooltipRectHeight/2); –

+0

http://jsfiddle.net/nCFGL/ 실행하면 아무 것도 표시되지 않습니다. – Kiquenet

3

각 영역의 값을 그래프 밖으로 표시 할 수 있도록 방법을 알아 냈습니다.

또한 I는 회전 값을 제거하고, I는 도넛 함수 내에서 코드의 다음 줄을 추가 here

함. (Chart.js 파일에서 수정 된 행을 붙여 넣었습니다.)

var Doughnut = function(data,config,ctx){ 

    var segmentTotal = 0; 

    //In case we have a canvas that is not a square. Minus 10 pixels as padding round the edge. 
    var doughnutRadius = Min([height/2,width/2]) - 15; 
    var cutoutRadius = doughnutRadius * (config.percentageInnerCutout/100); 
    //Modified for setting the label values out side the arc 
    var outRadius= doughnutRadius + cutoutRadius/3; 
    var outRadiustop= doughnutRadius + cutoutRadius/5; 
    ...... 
    ...... 
    ...... 

    function drawPieSegments (animationDecimal){ 
    : 
    : 



     if (config.scaleShowValues) { 
       ctx.save();     
       ctx.translate(width/2, height/2); 
       ctx.font = config.scaleFontStyle + ' ' + config.scaleFontSize + 'px ' + config.scaleFontFamily; 
       ctx.textBaselne = 'middle'; 
       var a = (cumulativeAngle + cumulativeAngle + segmentAngle)/2, 
        w = ctx.measureText(data[i].value).width, 
        b = Math.PI/2 < a && a < Math.PI * 3/2; 
       var c = 0 < a && a < Math.PI; 
       if(b){ 
        ctx.textAlign = 'right'; 
       } 
       else{ 
        ctx.textAlign = 'left'; 
       } 
       if(c){ 
        ctx.translate(Math.cos(a) * outRadius +1 , Math.sin(a) * outRadius+1); 

       } 
       else{ 
        ctx.translate(Math.cos(a) * outRadiustop, Math.sin(a) * outRadiustop);  
       } 

       ctx.fillStyle = config.scaleFontColor; 
       //If the segment angle less than 0.2, then the lables will overlap, so hiding it. 
       if(segmentAngle > 0.2){ 
        ctx.fillText(data[i].value,0,0); 

       } 
       ctx.restore(); 
    } 

    ...... 
    ...... 

이제 값이 각 섹션 밖으로 표시되고 회전되지 않습니다.

3

ChartNew은이 기능을 기본적으로 제공합니다. 당신이 ChartJS를 사용해야하는 경우

은 다음 잭의 솔루션 @ 의 수정 된 버전을 사용할 수 있습니다 :

Chart.types.Doughnut.extend({ 
    name: "DoughnutAlt", 
    draw: function() { 
     Chart.types.Doughnut.prototype.draw.apply(this, arguments); 
     this.chart.ctx.fillStyle = 'black'; 
     this.chart.ctx.textBaseline = 'middle'; 
     this.chart.ctx.fillText(this.segments[0].value + "%", this.chart.width/2 - 20, this.chart.width/2, 200); 
    } 
}); 
+1

의 전체 샘플을 _jsfiddle_에서 확인하십시오. *** Chart.types.Doughnut.extend *** – Kiquenet

7

이것은 말 그대로 시간과 시간이 걸렸다 내가 작업 솔루션을 발견했다.

https://github.com/nnnick/Chart.js/pull/116

내 마지막 코드이었다. 마스터 지점이 아니라 사람 포크 것이 아니다 나타납니다 - 당신이 https://github.com/Regaddi/Chart.js을 게시하는 풀에서 도넛

Chart.types.Doughnut.extend({ 
name: "DoughnutAlt", 
draw: function() { 
    Chart.types.Doughnut.prototype.draw.apply(this, arguments); 
    this.chart.ctx.fillStyle = 'black'; 
    this.chart.ctx.textBaseline = 'middle'; 
    this.chart.ctx.textAlign = 'start'; 
    this.chart.ctx.font="18px Verdana"; 

    var total = 0; 
    for (var i = 0; i < this.segments.length; i++) { 
     total += this.segments[i].value;  
    } 

    this.chart.ctx.fillText(total , this.chart.width/2 - 20, this.chart.height/2, 100); 
    for(var i = 0; i < this.segments.length; i++){ 
     var percentage = ((this.segments[i].value/total) * 100).toFixed(1); 
     if(percentage > 3){ 
      var centreAngle = this.segments[i].startAngle + ((this.segments[i].endAngle - this.segments[i].startAngle)/2), 
       rangeFromCentre = (this.segments[i].outerRadius - this.segments[i].innerRadius)/2 + this.segments[i].innerRadius; 
      var x = this.segments[i].x + (Math.cos(centreAngle) * rangeFromCentre); 
      var y = this.segments[i].y + (Math.sin(centreAngle) * rangeFromCentre); 
      this.chart.ctx.textAlign = 'center'; 
      this.chart.ctx.textBaseline = 'middle'; 
      this.chart.ctx.fillStyle = '#fff'; 
      this.chart.ctx.font = 'normal 10px Helvetica'; 
      this.chart.ctx.fillText(percentage , x, y); 
     } 
    } 
} 
}); 
+0

위대한 작품을 사용하여 나를 위해 일하지 않는다! 나는 차트를 초기화 할 때 커스텀 옵션의 전달을 처리하기 위해 이것을 [수정했다] (https://gist.github.com/frankfuu/392aaeb75d9d0bf53907)했다. 도넛 형 센터 내부에 총계를 보여주는 것을 삭제했습니다. –

+0

Chart.types가 나타납니다. 는 비어 있으므로 Chart.types.Doughnut.extend를 사용하여 이것을 확장 할 수 없습니다. 나는 각도 chartjs btw를 사용하고 있습니다. types 매개 변수가 비어 있거나 채워지는 이유는 무엇입니까? – EeKay