Chart.js - 悬停后的回调

时间:2013-10-14 14:10:07

标签: jquery charts

我需要在悬停图形的一部分后进行回调(donught)。我怎样才能做到这一点?从理论上讲,Chart.js不提供回调,因此这是一个问题:)

我目前的代码:

var visitorsChart = [
            {
                value: 60,
                color:'#3e89dc'
            },
            {
                value: 40,
                color:'#88c600'
            }
        ]

        var visitorsChartOptions = {
            percentageInnerCutout: 70
        }

        var renderVisitorsChart = new Chart(document.getElementById("visitors-chart").getContext("2d"), {tooltips: {position: 'bottom left', background: 'rgba(255,255,255,0)', fontFamily: 'Open Sans', fontSize: '40px', fontWeight: '700', labelTemplate:'<%=value%>'}, border: {width:0}, showShadow: false}).Doughnut(visitorsChart, visitorsChartOptions);

2 个答案:

答案 0 :(得分:0)

Charts.JS确实可以根据画布上发生的事件获取有关图表的信息。

http://www.chartjs.org/docs/#doughnut-pie-chart-prototype-methods

来自文档:

在Chart实例上调用getSegmentsAtEvent(event),传递事件或jQuery事件的参数,将返回与该事件位于同一位置的段元素。

canvas.onclick = function(evt){
    var activePoints = myDoughnutChart.getSegmentsAtEvent(evt);
    // => activePoints is an array of segments on the canvas that are at the same position as the click event.
};

此功能可用于实现基于DOM的工具提示,或触发应用程序中的自定义行为。

为悬停函数编写回调函数是很简单的,该函数可以访问图表中可能需要的信息。

$("#visitors-chart").mouseover(function (evt) {
    var info = renderVisitorsChart.getSegmentsAtEvent(evt.originalEvent);
    console.log(info);
});

答案 1 :(得分:0)

这是一种方法:

jQuery(window).load(function () {
    var doughnutChartData = [
        {
            value: 30,
            color: '#F7464A'
        },
        {
            value: 50,
            color: '#46BFBD'
        },
        // ...
    ];

    function showDoughnutChart() {
        var ctx = document.getElementById('doughnutChartCanvas').getContext('2d');
        var theChart = new Chart(ctx).Doughnut(doughnutChartData, {animation: Modernizr.canvas});

        // --- Part needed
        var helpers = Chart.helpers;

        helpers.bindEvents(theChart, ['mousemove', 'touchstart', 'touchmove', 'mouseout'], function (evt) {
            callback(theChart, evt);
        });
        // --- End part needed
    }

    var callback = function (theChart, evt) {
        if ((evt.type === 'mouseout')) {
            console.log('mouse out');
            return;
        }
        var activeSegments = theChart.getSegmentsAtEvent(evt);
        if (!activeSegments.length) return;

        console.log('mousemove', activeSegments[0])
    };

    $('#doughnutChart').appear(function () {
        $(this).css({opacity: 1});
        setTimeout(showDoughnutChart, 300);
    }, {accX: 0, accY: -155}, 'easeInCubic');
});