Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
503 views
in Technique[技术] by (71.8m points)

javascript - Draw a Chart.js with ajax data and responsive. A few problems and questions

I am using Chart.js (http://www.chartjs.org/docs/) for charting.

I need to get the data from an Ajax request and the chart to be responsive.

In my HTML code I added a canvas as follows:

<div>
  <canvas id="userscreated" class="plot" data-url="/stats/userscreated"></canvas>
</div>

And in my javascript (JQuery) code I have:

var data2;

$.ajax({
  url: $('#userscreated').data('url'),
  async: true,
  dataType: 'json',
  type: "get",
}).done(function (data) {

    data2 = data;

    // Draw chart
    var context = $('#userscreated').get(0).getContext("2d");
    var wrapper = $('#userscreated').parent();
    var width = $('#userscreated').attr('width', $(wrapper).width());

    new Chart(context).Line(
    {
      labels: data.Dates,
      datasets: [
        { fillColor: #404040, data: data.Users }
      ]
    },
    { animation: false }
  );

});

// Redraw the chart with the same data
$(window).resize(function () {

  var context = $('#userscreated').get(0).getContext("2d");
  var wrapper = $('#userscreated').parent();
  var width = $('#userscreated').attr('width', $(wrapper).width());

  new Chart(context).Line(
    {
      labels: data2.Dates,
      datasets: [
        { fillColor: #404040, data: data2.Users }
      ]
    },
    { animation: false }
  );

});

PROBLEMS

  1. The chart is not being resized on window resize.
  2. Is there better code to do this? I think I am repeating to much code.
  3. In Google the drawing is fast. In firefox sometimes it hangs for a while. Is anything wrong with my code?
  4. Should the request be async or not?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can make async AJAX calls no problem. It's just important that you setup the chart only after the success callback fires. Otherwise, you'll get issues with your canvas context not being defined. The first call to respondCanvas does the initial setup while the subsequent calls do the resizing.

Here is what works for me:

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

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).Line(chartData, {
        scaleOverride: true,
        scaleSteps: steps,
        scaleStepWidth: Math.ceil(max / steps),
        scaleStartValue: 0
    });
}

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();
});

If you want to insert a small delay between calls, you can use a timeout:

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

    GetChartData();
});

The delay will make your resizing more responsive in case you have a large dataset on your graph.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...