Random colors for stats graphs

This commit is contained in:
Antoine Bartuccio 2017-06-07 15:23:32 +02:00
parent 22945483d6
commit 801d287c0c
1 changed files with 44 additions and 18 deletions

View File

@ -37,7 +37,7 @@
{% for location in locations %}
<th>{{ location[1] }}</th>
{% endfor %}
<th>{% trans %}Total{% endtrans %}</th>
<th id="graphLabel">{% trans %}Total{% endtrans %}</th>
{% for type in subscriptions_types %}
<tr>
<td><i class="types" >{{ subscriptions_types[type]['name'] }}</i></td>
@ -61,38 +61,64 @@
{% block script %}
{{ super() }}
<script>
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function getRandomColorUniq(list) {
var color = getRandomColor();
while (list.includes(color)){
color = getRandomColor();
}
return color;
}
function hexToRgb(hex) {
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hex = hex.replace(shorthandRegex, function(m, r, g, b) {
return r + r + g + g + b + b;
});
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
var ctx = document.getElementById("statsChart").getContext('2d');
var labels = [];
var total = [];
var colors = [];
var colors_dimmed = [];
Array.from(document.getElementsByClassName("types")).forEach(function(element){
labels.push(element.childNodes[0].data);
});
Array.from(document.getElementsByClassName("total")).forEach(function(element){
total.push(element.childNodes[0].childNodes[0].data);
});
labels.forEach(function(element){
colors.push(getRandomColorUniq(colors));
});
colors.forEach(function(element){
var rgb_color = hexToRgb(element);
colors_dimmed.push('rgba(' + rgb_color.r + ', ' + rgb_color.g + ', ' + rgb_color.b + ', 0.2)');
});
console.log(colors);console.log(colors_dimmed);
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'Nombre de cotisations',
label: document.getElementById("graphLabel").childNodes[0].data,
data: total,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
backgroundColor: colors_dimmed,
borderColor: colors,
borderWidth: 1
}]
},