SamC
SamC

Reputation: 115

Creating Canvas Barchart from Dynamic Array Values

I am trying to create a bar chart from an array of elements that are dynamically created.

The current array list, chrr1 = [xxx, xxx, xxx, xxx, xxx, xxx, xxxx]. I have also checked with alert() that the canvas.height is set to 200 and h is being looped over and divided by 10 as in the function.

Yet the bar chart is not being created. I tried increasing the height but it didn't work. It's only showing one bar on the right side of the canvas (I could not upload the image here. The uploader doesn't seem to be working.)

var canvas = document.getElementById("ttmrev");
  var c = canvas.getContext("2d");
  c.fillStyle = "#000000";
  var currX = 0;
  var width = 30;
  for(j = 0; j < chrr1.length; j++) {
    var max_value = Math.max.apply(null, chrr1);
    var max_val_str = max_value.toString();
    if (max_val_str.length < 5) {
      canvas.height = "200";
    } else {
      canvas.height = "1000";
    }
    var h = chrr1[j];
    var g = h.toString();
    if (g.length < 5) {
      h = h/10;
    } else if (g.length >= 5) {
      h = h/100;
    } else if (!g || g.length === 0) {
      h = 0;
    }
    c.rect(currX, canvas.height - h, width, h);
    c.fill();
    currX += 40;
    }

Any help will be much appreciated.

Upvotes: 0

Views: 111

Answers (1)

ɢʀᴜɴᴛ
ɢʀᴜɴᴛ

Reputation: 32879

The issue is, you are resizing the canvas inside a for loop, which distorts the canvas, making all the previous drawings disappear.

You should rather do the canvas resizing stuff outside the for loop, like so ...

var canvas = document.getElementById("ttmrev");
var c = canvas.getContext("2d");
var currX = 0;
var width = 40;
chrr1 = [333, 222, 666, 1200, 444, 1000];

var max_value = Math.max.apply(null, chrr1);
var max_val_str = max_value.toString();
if (max_val_str.length < 5) {
    canvas.height = 200;
} else {
    canvas.height = 1000;
}

for (j = 0; j < chrr1.length; j++) {
    var h = chrr1[j];
    var g = h.toString();
    if (g.length < 5) {
        h = h / 10;
    } else if (g.length >= 5) {
        h = h / 100;
    } else if (!g || g.length === 0) {
        h = 0;
    }
    c.rect(currX, canvas.height - h, width, h);
    c.fillStyle = "#000000";
    c.fill();
    currX += 52;
}
body{margin:10px 0 0 0;overflow:hidden}canvas{border:1px solid #e4e6e8}
<canvas id="ttmrev"></canvas>

Upvotes: 2

Related Questions