1

I created a chart on my page using ChartJs and then i placed three buttons so that when clicked, it represents the data in a different chart type. but the issue i am having is that if i move the mouse pointer across the canvas after switching to a different graph, it keeps switching or flickering and this is not good, how can i get it to stay on the current chart type.

i tried clearing the canvas and context object before rendering the chart but yet, it still refuses to work, here's my code..

var chartx;
var cv;


var mnts, vals, mx, steps; // for the chart labels.. 

//retrieve the json data from this url.. var setting = { type:'GET', url:'/ajax/stats/summary' };

$(function(){
  'use strict';  

  cv = document.getElementById('dboard');  //the canvas object
  pullChartData('line');                  //draw the line graph first

});

function pullChartData(chtype){

   shwChldx();     //show the GIF loader 
   clearCanvas();  //clear the canvas

   $.ajax(setting)
    .done(function(response){       
       o = JSON.parse(response);

       mnts = String(o.days).split(';');   //array of horizontal labels
       vals = String(o.values).split(';'); //array of values
       mx = Number(o.mx);                  //maximum value among chart data
       steps = Number(o.step);             //get the step to use on chart

       setChartType(chtype);
       hideChldx()

    }).fail(function(xhr,status,error){

       hideChldx();
       notifyCVS('error loading CHART data...');

    });
}


function shwChldx(){   //show loader GIF 
  $('#tkldr').css('display', 'block');
}


function hideChldx(){     //hide loader GIF
  $('#tkldr').css('display', 'none');
}


function drawChart(cdiv, ctype){  //draw graph function

    chartx = new Chart(cdiv, {
                    type: ctype,
                    data: {
                      labels: mnts,     
                      datasets: [{
                        data: vals,
                        label: ' - visits at on this day',
                        borderColor: '#324463',
                        fillColor: 'rgba(109,177,117,0.71)',
                        borderWidth: 1,
                        fill: true
                      }]
                    },

                    options: {

                          backgroundColor: '#FFF',
                          titleFontSize: 16,
                          titleFontColor: '#0066ff',
                          titleMarginBottom: 10,
                          bodyFontColor: '#000',
                          bodyFontSize: 12,
                          displayColors: false,
                          xPadding:10,
                          yPadding:10,

                      },

                      legend: {
                        display: false,
                          labels: {
                            display: false
                          }
                      },
                      scales: {
                        yAxes: [{
                          ticks: {
                            beginAtZero:true,
                            fontSize: 12,
                            max: mx,
                            stepSize: Number(steps),
                          }
                        }],
                        xAxes: [{
                          ticks: {
                            beginAtZero:true,
                            fontSize: 11
                          }
                        }]
                      }
                    }
               });

          }
//clear the canvas object before anything.. 
function clearCanvas(){
  ctx = cv.getContext('2d');
  ctx.clearRect(0, 0, cv.width, cv.height);
  notifyCVS('retrieving data, please wait...');
}

   //this is the function referenced on the buttons.. 
   //example - <button onclick="setChartType('bar')"></button> 
   // and i have 3 buttons for 'line', 'bar', 'horizontalBar' types

function setChartType(type){
  clearCanvas();
  ctx = cv.getContext('2d');
  ctx.clearRect(0, 0, cv.width, cv.height);
  drawChart(cv, type);
}

//i call this function to write on the canvas when there is 
//no activity so that its not just a blank white object..

function notifyCVS(txt){
  ctx = cv.getContext('2d');
  ctx.clearRect(0, 0, cv.width, cv.height);
  ctx.fillStyle = "#777777";
  ctx.font = "Regular 12px Arial";
  ctx.fillText(String(txt), (cv.width / 2) - 17, (cv.height / 2) + 8);
}

so this is my approach, the chart and everything works, but after clicking the different buttons the behaviour changes on mousemove and i dont know where the problem is from, thats just the problem, the flickering behaviour.

please what should i do.

1 Answer 1

4

There is no need to literally clear the canvas. But you need to destroy the chartjs object before you reinitialize it. So, it's like re-creating a chartjs object on the same canvas. All you need to do is check if the instance already exists before creating the object in drawChart method.

function drawChart(cdiv, ctype){
      if(chartx){
            chartx.destroy();
      }
      chartx = new Chart(.....
      ...... 
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.