Jimmy Page Jimmy Page - 2 years ago 92
JSON Question

Strange issue with Chart.js bar chart, image scattering

I've included in my HTML page a stacked bar graphic (with the Chart.js library) that makes user visualize some data. These data change on selection of the user, the Javascript function that enables this onclick feature is:

function aggLav(){
for(i=2; i<src.rows.length-1; i++){
cells[i].onclick = function () {//load graphic
makeGrafico(dati, this.innerHTML);
var gr=document.getElementById("canvas");
if($(gr).is(':hidden')) $(gr).slideToggle();

where the function createData creates the JSON object (with labels and datasets) to pass to the graphic (works fine), and the function makeGrafico():

function makeGrafico(dati, titolo){
var d=getFirstMonday();
var mondays=[];
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx, {
type: 'bar',
data: dati,
options: {
text:titolo//change to name of procedure
tooltips: {
mode: 'label'
responsive: true,
scales: {
xAxes: [{
stacked: true,
yAxes: [{
stacked: true

takes the name of the parameter in order to display it, and the JSON object of the previous function.

When i first click on one procedure (the cell with the onclick feature rapresents an industrial procedure, not relevant), everything goes just fine, the graphic slides up and show the correct result. But when i click on another procedure, i expect to see the graphic related to that procedure: this is true, but when i move the mouse over the image, the graphic suddenly changes, making me see for a while the data of the first procedure i clicked.

In general, if i click 10 different procedures, and i hover the mouse on the graphic, i see all the 10 graphics alterning each other. If i manage to find the spot on where the graphic changes, it rests changed for all the time i leave the pointer on that position.

I'd surely like to make the data (and the graphic) be persistent, and relative to the last procedure i clicked.

How to solve this weird issue? Am i missing something? I'm new to this library.

Answer Source

You might be interested by this post. You need to clear the canvas at the beginning of your makeGrafico function.

In a first time, you should try adding window.myBar.destroy(). If it does not work, you should consider deleting the canvas element and to create it again :

var $parent = $('#canvas').parent();
$parent.append('<canvas id="canvas"></canvas>');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download