多个图表呈现在彼此之上

时间:2014-05-02 18:55:58

标签: javascript knockout.js knockout-validation durandal-2.0 chart.js

我已经获得了一些图表数据,我通过AJAX调用加载并使用支持工具提示的修改后的Chart.js进行显示。它适用于第一次调用,但是当我通过更改日期范围进行后续调用时,它会在旧图表数据的基础上绘制新的图表数据。我已将我的图表刷新代码放入窗口调整大小事件中,以便它可以响应。然而,事实上这可能是导致问题的原因。这是我的代码:

var BreakDowns = [
    'Daily',
    'Weekly',
    'Monthly',
    'Quarterly',
    'Yearly'
];

var BreakDown = ko.observable(BreakDowns[0]);
BreakDown.subscribe(function (newValue) {
    switch (newValue) {
        case 'Daily':
            EndDate(StartDate());
            break;
        case 'Weekly':
            EndDate(moment(StartDate()).add('d', 7).format('MM/DD/YYYY'));
            break;
        case 'Monthly':
            EndDate(moment(StartDate()).add('M', 1).format('MM/DD/YYYY'));
            break;
        case 'Quarterly':
            EndDate(moment(StartDate()).add('M', 3).format('MM/DD/YYYY'));
            break;
        case 'Yearly':
            EndDate(moment(StartDate()).add('y', 1).format('MM/DD/YYYY'));
            break;
    }
    GetChartData();
});

var date = new Date();

var StartDate = ko.observable(moment(date).format('MM/DD/YYYY'));
var EndDate = ko.observable(moment(date).format('MM/DD/YYYY'));

var Form = ko.validatedObservable({
    StartDate: StartDate.extend({ isDate: true }),
    EndDate: EndDate.extend({ isDate: true })
});      

StartDate.subscribe(function (newValue) {
    GetChartData();
});

EndDate.subscribe(function (newValue) {
    GetChartData();
});


var chart = {};

var GetChartData = function () {
    if (Form.isValid()) {
        $.ajax({
            url: serviceUri + 'api/Document/ChartData/?breakdown=' + BreakDown().toLowerCase() + '&startDate=' + StartDate() + '&endDate=' + EndDate(),
            method: 'GET',
            dataType: 'json',
            success: function (d) {   
                var chartData = {
                    labels: d.AxisLabels,
                    datasets: [
                        {
                            fillColor: "rgba(220,220,220,0.5)",
                            strokeColor: "rgba(220,220,220,1)",
                            pointColor: "rgba(220,220,220,1)",
                            pointStrokeColor: "#fff",
                            data: d.DataSets[0]
                        }
                    ]
                };

                var max = Math.max.apply(Math, d.DataSets[0]);
                var steps = 10;

                var c = $('#summary');
                var ctx = c.get(0).getContext("2d");
                var container = c.parent();

                $(window).resize(respondCanvas);

                function respondCanvas() {
                    var $container = $(container);
                    if ($container.width() >= 900)
                        c.attr('width', $container.width());
                    else
                        c.attr('width', 900);

                    if ($container.height() >= 400)
                        c.attr('height', $container.height());                
                    else
                        c.attr('height', 400);

                    ctx.width = ctx.width;

                    //Call a function to redraw other content (texts, images etc)
                    chart = new Chart(ctx).Bar(chartData, {
                        scaleOverride: true,
                        scaleSteps: steps,
                        scaleStepWidth: Math.ceil(max / steps),
                        scaleStartValue: 0,
                        annotateDisplay: true
                    });
                }

                respondCanvas();
            }
        });
    }
}

以下是生成的图表的图像: Mangled chart

如何让Chart.js不绘制先前的数据并绘制新图表?

1 个答案:

答案 0 :(得分:0)

$(window).resize(respondCanvas)移出我的AJAX成功回调后,这是我所拥有的简化版本:

var chartData = {};
var max = 0;
var steps = 10;

function respondCanvas() {
    var c = $('#summary');
    var ctx = c.get(0).getContext("2d");
    var container = c.parent();

    var $container = $(container);

    c.attr('width', $container.width()); //max width

    c.attr('height', $container.height()); //max height                   

    //Call a function to redraw other content (texts, images etc)
    var chart = new Chart(ctx).Bar(chartData, {
        scaleOverride: true,
        scaleSteps: steps,
        scaleStepWidth: Math.ceil(max / steps),
        scaleStartValue: 0,
        annotateDisplay: true
    });
}

var GetChartData = function () {
    $.ajax({
        url: serviceUri,
        method: 'GET',
        dataType: 'json',
        success: function (d) {
           chartData = {
                labels: d.AxisLabels,
                datasets: [
                    {
                        fillColor: "rgba(220,220,220,0.5)",
                        strokeColor: "rgba(220,220,220,1)",
                        pointColor: "rgba(220,220,220,1)",
                        pointStrokeColor: "#fff",
                        data: d.DataSets[0]
                    }
                ]
            };

            max = Math.max.apply(Math, d.DataSets[0]);
            steps = 10;

            respondCanvas();
        }
    });
};

$(document).ready(function() {
    $(window).resize(respondCanvas);

    GetChartData();
});

注意,如果要在更新之间插入一个小延迟,可以使用超时:

$(document).ready(function() {
    $(window).resize(setTimeout(respondCanvas, 500));

    GetChartData();
});