SimpleHTML5CanvasBarChart
Very basic bar chart using HTML canvas
by Simon Raper
HTML
<body>
<canvas id="myCanvas" width="650" height="400" style="border:1px solid #000000;"></canvas>
</body>
JavaScript
//Data
var data = [100, 550, 320, 790, 1500, 1345, 345, 123, 458, 2230, 42, 1000];
var labels = ["100k", "200K", "300K", "400K", "500K", "600K", "700K", "800K", "900k", "1000K", "1100K", "1200K"];
//Get canvas
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
//Draw axes
ctx.moveTo(50, 300);
ctx.lineTo(50, 50);
ctx.moveTo(50, 300);
ctx.lineTo(550, 300);
ctx.stroke();
//Draw ticks
for (var i = 1; i <= 13; i++) //x-axis
{
x = 50 + 35 * i;
ctx.moveTo(x, 300);
ctx.lineTo(x, 310);
}
for (var i = 1; i <= 4; i++) //y-axis
{
y = 300 - 50 * i;
ctx.moveTo(50, y);
ctx.lineTo(45, y);
}
//Draw y labels
ctx.font = "11px Arial";
ctx.textAlign="end";
for (var i = 1; i <= 4; i++) //y-axis
{
y = 300 - 50 * i;
//ctx.moveTo(20, y);
ctx.fillText(i*500, 40, y+3);
}
ctx.textAlign="start";
ctx.stroke();
//function to draw a bar
function drawBar(x, y, h, l) {
ctx.fillStyle = "purple";
ctx.fillRect(x, y - h, 30, h);
//Draw label
ctx.translate(x + 15, y + 20);
ctx.rotate(Math.PI / 2);
ctx.font = "11px Arial";
//ctx.fillText(l, y+20, x+5);
ctx.fillText(l, 0, 0);
ctx.rotate(-Math.PI / 2);
ctx.translate(-(x + 15), -(y + 20));
}
//Draw the bars
for (var i = 1; i <= 12; i++) {
x = 50 + 35 * i;
drawBar(x, 295, data[i - 1] / 10, labels[i - 1]);
}