Reputation: 58642
I have charts
<div class="col-xs-2"><canvas id="device"></canvas></div>
<div class="col-xs-2"><canvas id="host_name"></canvas></div>
<div class="col-xs-2"><canvas id="city"></canvas></div>
<div class="col-xs-2"><canvas id="org"></canvas></div>
<div class="col-xs-2"><canvas id="country"></canvas></div>
<div class="col-xs-2"><canvas id="region"></canvas></div>
<style type="text/css">
.chart-inner {
margin-top: -100px;
margin-bottom: 100px;
}
.chart-inner h5 {
margin-bottom: 5px;
margin-top: 27px;
font-size: 200px;
color: red;
}
</style>
I've tried to append text to the center
$('canvas#' + selector).append('<div class="chart-inner"><h5>' + selector + '</h5></div>');
It doesn't seem to come through.
But when I hide(), it works. All charts are hidden.
$('canvas#' + selector).hide();
What am I missing ?
<script>
function renderChart(selector, chartType, colors, labels, values, chartLine ) {
let chart = document.getElementById(selector).getContext('2d');
new Chart(chart, {
type:chartType, // bar, horizontalBar, pie, line, doughnut, radar, polarArea
data:{
labels:labels,
datasets:[{
data:values,
// backgroundColor:colors,
backgroundColor:colors,
borderWidth:1,
borderColor:'white',
hoverBorderWidth:2,
hoverBorderColor:colors,
hoverBorderWidth: 2,
borderAlign: 'inner',
}]
},
options:{
title:{
display:true,
text:selector
},
legend:{
display:false,
position:'right',
labels:{
fontColor:'#000'
}
},
cutoutPercentage: 70,
animation:{
animateScale:true,
},
}
});
// $('canvas#' + selector).append('<div class="chart-inner"><h5>' + selector + '</h5></div>');
// $('canvas#' + selector).hide();
//$('canvas#device').append('<div class="chart-inner"><h5>1234</h5></div>');
}
/*=========================================
= deviceType =
=========================================*/
var ajax = $.ajax({url: '/visitor/summary/device'});
ajax.done(function (response) {
deviceTypeLabels = [];
deviceTypeValues = [];
$.each(response, function(key,val) {
deviceTypeLabels.push(key);
deviceTypeValues.push(val);
});
renderChart('device', 'doughnut', colors, deviceTypeLabels, deviceTypeValues );
});
... and more charts ...
</script>
Upvotes: 2
Views: 802
Reputation: 443
I've tried to append text to the center
You're appending elements inside of the canvas
tag. That's only displayed as a fallback when your browser lacks canvas support.
What you're looking for is using the canvas getContext
method.
Adapted to what you provided, it would go something like this:
var centerX = chart.width / 2;
var centerY = chart.height / 2;
chart.fillStyle = 'black';
chart.font = '200px';
chart.textAlign = 'center';
chart.fillText(selector, centerX, centerY);
You may need to offset centerX or centerY depending on how the width of your doughnut charts is calculated.
Upvotes: 4