2017-03-03 1 views
0

현재 도넛의 중간에 맴돌고있는 도넛 세그먼트의 비율을 그려야합니다.도넛이있는 도넛 중간에 원형 세그먼트 비율을 그리기

저는 chartjs 2를 사용하고 있으므로 플러그인을 살펴보고 있습니다. on the documentation은 "afterEvent"- "캔버스에서 이벤트가 발생하면 (mousemove, click, etc.) 호출 할 수있는 플러그인 중 하나입니다.이 옵션을 처리하려면 options.events 속성이 필요합니다." 페이지의 코드는 다음과 같습니다.

afterEvent: function(chartInstance, event) {} 

그러나 afterEvent 상태를 사용하는 방법을 잘 모르겠습니다. 나는 도형 중간에 그림을 그려 넣었다. 예제는 such as this이다. 그러나 'beforeDraw'대신 'afterEvent'에이 코드를 실행할 수 있기를 원합니다. 'event'매개 변수에 어떤 이벤트 데이터가 들어 있는지에 관한 문서가 있습니까? 호버링 이벤트 인 경우 'onHover'와 동일한 방식으로 호버링되고있는 세그먼트의 가치를 나에게 줄 수 있습니까?

어디서나 더 이상 설명서를 찾을 수 없습니다. 누군가가 나를 올바른 방향으로 인도 할 수 있다면 좋을 것입니다.

감사합니다.

답변

1

플러그인을 통해 구현할 가능성이 높지만, 똑같은 동작을 제공하는 대체 방법이 있습니다.

기본적으로 차트 세그먼트가 배치 될 때 트리거되는 차트 중간에 배치 된 외부 사용자 지정 도구 설명을 사용합니다.

다음은 관련 코드

Chart.defaults.global.tooltips.custom = function(tooltip) { 
    // Tooltip Element 
    var tooltipEl = document.getElementById('chartjs-tooltip'); 

    // Hide if no tooltip 
    if (tooltip.opacity === 0) { 
    tooltipEl.style.opacity = 0; 
    return; 
    } 

    // Set Text 
    if (tooltip.body) { 
    var total = 0; 

    // get the value of the datapoint 
    var value = this._data.datasets[tooltip.dataPoints[0].datasetIndex].data[tooltip.dataPoints[0].index].toLocaleString(); 

    // calculate value of all datapoints 
    this._data.datasets[tooltip.dataPoints[0].datasetIndex].data.forEach(function(e) { 
     total += e; 
    }); 

    // calculate percentage and set tooltip value 
    tooltipEl.innerHTML = '<h1>' + (value/total * 100) + '%</h1>'; 
    } 

    // calculate position of tooltip 
    var centerX = (this._chartInstance.chartArea.left + this._chartInstance.chartArea.right)/2; 
    var centerY = ((this._chartInstance.chartArea.top + this._chartInstance.chartArea.bottom)/2); 

    // Display, position, and set styles for font 
    tooltipEl.style.opacity = 1; 
    tooltipEl.style.left = centerX + 'px'; 
    tooltipEl.style.top = centerY + 'px'; 
    tooltipEl.style.fontFamily = tooltip._fontFamily; 
    tooltipEl.style.fontSize = tooltip.fontSize; 
    tooltipEl.style.fontStyle = tooltip._fontStyle; 
    tooltipEl.style.padding = tooltip.yPadding + 'px ' + tooltip.xPadding + 'px'; 
}; 

그리고뿐만 아니라 working example이다.

+0

아쉽습니다. 커스텀 툴팁 접근법을 사용하지 않을 것 같습니다. 그게 바로 내가 찾고있는 것이고, 캔버스가 아닌 CSS로 스타일링되는 이점이 있습니다. 다시 한 번 감사드립니다! – poncho

+0

안녕하세요, 저는 이제 내 자신의 차트로 구현하려고 시도 했으므로 문제가 발생했습니다. 어떤 이유로 tooltip.dataPoints가 존재하지 않습니다. Inspect 요소를 수행하고 해당 줄에 중단 점을 넣었습니다. 툴팁 객체에 포함 된 내용을 볼 때 dataPoints가 없습니다. 내가 설정하지 못한 설정이 있습니까? 내 코드와 코드가 동일하게 보입니다 - 사용하는 동안 내 차트 데이터가 업데이트되는 것 외에 (데이터 포인트의 새로운 배열에서 "데이터"를 포스팅 한 후 업데이트() 할 때처럼) 문제가 될 수 있습니까? – poncho

+0

지난 코멘트를 무시하면 툴팁에 datapoints 속성이없는 chartjs 2.1이 사용 된 것으로 나타났습니다. 2.5로 변경 한 후 완벽하게 작동합니다. 다시 한 번 감사드립니다! – poncho

관련 문제