-
Notifications
You must be signed in to change notification settings - Fork 0
/
ezbc.js
80 lines (73 loc) · 2.55 KB
/
ezbc.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*
* Easy Bar Charts
*
* https://github.com/patrick-east/EZBC-js
*
* This only makes vertical stacked bar charts. The will be the size of
* whatever container you draw it in. It does not retain data, handle
* resize, make other types of graphs, deliver beer, or anything special.
*/
var EZBC = (function () {
var chart = {};
/*
* Expect a container element reference and data in the format of:
* [
* {
* value: 50,
* color: "#FF00FF",
* label: "wins",
* border: true,
* borderColor: "#000000"
* },
* {
* value: 10,
* color: "yellow",
* label: "loses"
* },
* ]
*
* Note: The order of elements is how they will be drawn from bottom to top.
*/
chart.draw = function (container, data) {
var totalValue = 0;
for (var i = 0; i < data.length; i++) {
totalValue += data[i]['value'];
// check for some 'required' fields and try some defaults...
if (!data[i].hasOwnProperty('color')) {
data[i].color = '#'+Math.floor(Math.random()*16777215).toString(16);
}
if (!data[i].hasOwnProperty('border')) {
data[i].border = false;
}
else if (!data[i].hasOwnProperty('borderColor')) {
data[i].borderColor = '#000000';
}
}
var chartHeight = parseFloat(container.style.height);
var chartWidth = parseFloat(container.style.width);
var chartSVG = '<svg ';
chartSVG += 'width="' + chartWidth + '" ';
chartSVG += 'height="' + chartHeight + '" ';
chartSVG += '>';
var currentY = chartHeight;
for (var i = 0; i < data.length; i++) {
var rectHeight = Math.round(chartHeight * (data[i].value / totalValue));
chartSVG += '<rect ';
chartSVG += 'width="' + chartWidth + '" ';
chartSVG += 'height="' + currentY + '" ';
chartSVG += 'style="fill:' + data[i].color + ';';
if (data[i].border) {
chartSVG += 'stroke-width:2;stroke:' + data[i].borderColor + ';';
}
chartSVG += '">';
if (data[i].hasOwnProperty('label')) {
chartSVG += '<title>' + data[i].label + '</title>';
}
chartSVG += '</rect>';
currentY -= rectHeight;
}
chartSVG += '</svg>';
container.innerHTML = chartSVG;
};
return chart;
}());