Created
February 24, 2014 15:06
-
-
Save PifyZ/9189975 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function() { | |
function bar_chart(el, datas) { | |
// Récupération de la zone de dessin | |
var can = document.getElementById(el); | |
var ctx = can.getContext('2d'); | |
// Récupération de la valeur maximale | |
var max_of_array = 0; | |
for (var i = 0, nb_datas = datas.length ; i < nb_datas ; i++) { | |
if (datas[i][0] > max_of_array) | |
max_of_array = datas[i][0]; | |
} | |
// Déterminaison de la taille de la zone de dessin | |
var offset_negative = 58; | |
can.height = 98 + offset_negative; | |
can.width = 188; | |
// Affichage et calcul de la zone de dessin | |
function create() { | |
var x, y, w, h, data, nb, date; | |
// Définition de la police des nombres au dessus des barres | |
ctx.textAlign = 'center'; | |
ctx.font = '13px Calibri'; | |
// Affichage des barres, des nombres et des dates | |
for (var i = 0, nb_datas = datas.length ; i < nb_datas ; i++) { | |
data = datas[i]; | |
nb = data[0]; | |
date = data[1]; | |
// Calcul des positions | |
w = 12; | |
h = Math.max(nb * 75 / max_of_array, 0); | |
x = i * (w + 2) + 16; | |
y = can.height - h - offset_negative; | |
ctx.fillStyle = 'rgb(50, 150, 0)'; | |
// Affichage de la barre | |
if (h > 0) | |
ctx.fillRect(x, y, w, h); | |
if (nb > 0) | |
ctx.fillStyle = 'rgb(50, 150, 0)'; | |
else if (nb < 0) | |
ctx.fillStyle = 'rgb(150, 50, 0)'; | |
else | |
ctx.fillStyle = 'rgb(0, 0, 0)'; | |
// Affichage du nombre | |
if (nb > 0) | |
ctx.fillText('+', x + 6, y - 16); | |
else if (nb < 0) | |
ctx.fillText('-', x + 6, y - 10); | |
ctx.fillText(Math.abs(nb), x + 6, y - ((nb > 0) ? 5 : 0)); | |
// Affichage de la date (ou non) | |
if (i % 2 == 1) { | |
ctx.save(); | |
ctx.translate((i + 1) * 14 + 2, can.height - offset_negative + 30); | |
ctx.rotate(-60 * Math.PI / 180); | |
ctx.fillStyle = 'rgb(0, 0, 0)'; | |
ctx.font = '12px Calibri'; | |
ctx.fillText(date, 0, 0); | |
ctx.restore(); | |
} | |
} | |
} | |
create(); | |
} | |
window.bar_chart = bar_chart; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment