Always show doughnut Chart tooltip in Angular 5 - javascript

I need to always show tooltip for a doughnut Chart so I need to add this:
Chart.pluginService.register({
beforeRender: function(chart) {
if (chart.config.options.showAllTooltips) {
// create an array of tooltips
// we can't use the chart tooltip because there is only one tooltip per chart
chart.pluginTooltips = [];
chart.config.data.datasets.forEach(function(dataset, i) {
chart.getDatasetMeta(i).data.forEach(function(sector, j) {
chart.pluginTooltips.push(new Chart.Tooltip({
_chart: chart.chart,
_chartInstance: chart,
_data: chart.data,
_options: chart.options.tooltips,
_active: [sector]
}, chart));
});
});
// turn off normal tooltips
chart.options.tooltips.enabled = false;
}
},
afterDraw: function(chart, easing) {
if (chart.config.options.showAllTooltips) {
// we don't want the permanent tooltips to animate, so don't do anything till the animation runs atleast once
if (!chart.allTooltipsOnce) {
if (easing !== 1)
return;
chart.allTooltipsOnce = true;
}
// turn on tooltips
chart.options.tooltips.enabled = true;
Chart.helpers.each(chart.pluginTooltips, function(tooltip) {
tooltip.initialize();
tooltip.update();
// we don't actually need this since we are not animating tooltips
tooltip.pivot();
tooltip.transition(easing).draw();
});
chart.options.tooltips.enabled = false;
}
}
});
https://jsfiddle.net/suhaibjanjua/qz3es03j/
In Angular 5 and I don't really know how to translate that code inside a component.ts.
I also need to add a small black border to each tooltips. I know how to do that in css but I don't know how to add it to chart tooltips.
this is my current component.ts code:
doughnutChartData: any[] = [0,18,26,16, 40];
doughnutChartLabels: any[] = ['NA', 'NE', 'NO', 'C', 'S'];
doughnutChartOptions: any = {
responsive: true,
maintainAspectRatio: false,
cutoutPercentage: 80,
tooltips: {
enabled: true,
backgroundColor: 'white',
titleFontColor: 'black',
bodyFontColor: 'black',
xPadding: 20,
yPadding: 20,
displayColors: false,
callbacks: {
label: function(tooltipItem, data) {
var allData = data.datasets[tooltipItem.datasetIndex].data;
var tooltipLabel = data.labels[tooltipItem.index];
var tooltipData = allData[tooltipItem.index];
var total = 0;
for (var i in allData) {
total += allData[i];
}
var tooltipPercentage = Math.round((tooltipData / total) * 100);
return tooltipLabel + ': ' + tooltipPercentage + '%';
}
}
}
};
doughnutChartColors: any[] = [{
borderWidth: 3,
backgroundColor: ['#ffffff', '#e827d3', 'black', 'rgb(104, 104, 104)', 'gray']
}];
And the html:
<mat-card class="charts-npls first-chart">
<canvas baseChart
[data]="doughnutChartData"
[labels]="doughnutChartLabels"
[options]="doughnutChartOptions"
[colors]="doughnutChartColors"
[legend]="false"
chartType="doughnut">
</canvas>
</mat-card>

Ok I was able to find an answer by using this as an example:
https://embed.plnkr.co/opFmFg34AyqVwgvdda0Z?show=preview
declare var Chart: any;
ngOnInit() : void{
Chart.pluginService.register({
beforeDraw: (chart) => {
if (chart.config.options.showAllTooltips) {
// create an array of tooltips
// we can't use the chart tooltip because there is only one tooltip per chart
chart.pluginTooltips = [];
chart.config.data.datasets.forEach(function(dataset, i) {
chart.getDatasetMeta(i).data.forEach(function(sector, j) {
chart.pluginTooltips.push(new Chart.Tooltip({
_chart: chart.chart,
_chartInstance: chart,
_data: chart.data,
_options: chart.options.tooltips,
_active: [sector]
}, chart));
});
});
// turn off normal tooltips
chart.options.tooltips.enabled = false;
}
},
afterDraw: (chart, easing) => {
if (chart.config.options.showAllTooltips) {
// we don't want the permanent tooltips to animate, so don't do anything till the animation runs atleast once
if (!chart.allTooltipsOnce) {
if (easing !== 1)
return;
chart.allTooltipsOnce = true;
}
// turn on tooltips
chart.options.tooltips.enabled = true;
Chart.helpers.each(chart.pluginTooltips, function(tooltip) {
tooltip.initialize();
tooltip.update();
// we don't actually need this since we are not animating tooltips
tooltip.pivot();
tooltip.transition(easing).draw();
});
chart.options.tooltips.enabled = false;
}
}
});
}
And I added:
showAllTooltips: true,
to the doughnutChartOptions
Ok, to add a border to tooltips just add:
borderColor: 'rgba(0,0,0,1)',
borderWidth: 1,
caretSize: 0,
carterSize 0 will also remove the carter so that you will get a nice rectangle.

Related

Chart.js Console JS Error while destroy the Chart on click event

on Bar click event of first chart "config.categoriesChart" gets the console error "chart.js:10403 Uncaught TypeError: Cannot read property 'handleEvent' of undefined"
enter image description here which diplayed as chart.legend.handleEvent(args.event);
The issue happens after destroy the First chart on the bar click Event of first chart.
But if I use $('#how_i_spend_canvas').replaceWith($(''));
its working fine without destroy the chart.
enter image description here
Please let me what is the issue?
All code in document.ready
let Chart = require('chart.js');/
let ChartDataLabels = require('chartjs-plugin-datalabels');
let config = window.MvpFE.globalConfiguration.howISpend;
let dataChart = window.dataHowISpendCharts;
let labels = dataChart.howISpendDataCatgories.map(function (e) {
return e.label;
});
let data = dataChart.howISpendDataCatgories.map(function (e) {
return e.data;
});
//Chart Axis's
let scales = {
x: {
ticks: {
font: {
size: config.size,
},
color: config.dataLabelsColor,
},
},
y: {
display: false,
}
};
//Chart legend
let plugins = {
legend: {
display: false,
},
tooltip: {
enabled: true,
},
};
//Chart Data Labels
let dataLabels = {
color: config.dataLabelsColor,
anchor: 'end',
align: 'top',
offset: 0,
formatter: function (value) {
//Include a dollar sign
return '$' + value.toLocaleString();
},
};
//chart data
let howISpendChartdata = {
labels: labels,
datasets: [{
data: data,
backgroundColor: config.catogriesBackgroundColor,
borderColor: config.catogriesBorderColor,
hoverBackgroundColor: config.unSelectedColor,
hoverBorderColor: config.unSelectedColor,
borderWidth: config.barWidth,
borderRadius: config.barRadius,
borderSkipped: 'false',
datalabels: dataLabels
}]
}
// Category heading label text will be from json data
let categoryLabel = "";
//Array to store the bar background colors.
const barColors = [];
//Code to draw Chart
var ctx = document.getElementById('how_i_spend_canvas').getContext('2d');
config.categoriesChart = new Chart(ctx, {
type: 'bar',
data: howISpendChartdata,
// Chart pulgins & Options
plugins: [ChartDataLabels],
options: {
responsive: true,
maintainAspectRatio: false,
aspectRatio: 2,
plugins: plugins,
scales: scales,
onClick: function (evt, element) {
if (element.length > 0) {
const categoriesChart = config.categoriesChart;
let activeBarIndex = element[0].index;
categoryLabel = categoriesChart.data.labels[activeBarIndex];
// destroy any chart instances that are created
if (categoriesChart instanceof Chart) {
categoriesChart.destroy();
}
//$('#how_i_spend_canvas').replaceWith($('<canvas id="SelectedCategory" height="400px"></canvas>')); //replace current canvas
// Code to draw Chart
config.monthlyChart = new Chart(ctx, {
type: 'bar',
data: howISpendChartdata,
plugins: [ChartDataLabels],
options: {
responsive: true,
maintainAspectRatio: false,
aspectRatio: 2,
plugins: plugins,
scales: scales,
onClick: function (e, activeElements) {
//get the colors for bars
if (activeElements.length > 0) { // check the element is selected
const monthlyChart = config.monthlyChart;
monthlyChart.options.animation.colors = false;
monthlyChart.update();
}
}
}
},
});
config.monthlyChart.render();
}
},
}
}); // document.Ready Ends()
WARNING: This solution makes sense only if you're not using the legend plugin or don't need to handle legend item click event.
In my case I was getting this error even though I disabled legend plugin in chart options, like this:
plugins: {
legend: {
display: false
}
}
The error stopped happening after I filtered events handled by the legend plugin, like this:
plugins: {
legend: {
display: false,
events: [] // this line was the key
},
}
I came accros the same issue, reason for the exception is:
Inside the onclick event if you try to destroy the same chart, chart reference becomes null before the event callback function returns. And that's why exception is thrown.
You can fix this by destroying the chart instance after the event callback is completed i.e. using setTimeout function you can destroy the chart after 100ms or so. you can do it like this:
options: {
onClick: function (evt, element) {
if (element.length > 0) {
const categoriesChart = config.categoriesChart;
let activeBarIndex = element[0].index;
categoryLabel = categoriesChart.data.labels[activeBarIndex];
setTimeout(() => {
// destroy any chart instances that are created
if (categoriesChart instanceof Chart) {
categoriesChart.destroy();
}
//$('#how_i_spend_canvas').replaceWith($('<canvas id="SelectedCategory" height="400px"></canvas>')); //replace current canvas
// Code to draw Chart
config.monthlyChart = new Chart(ctx, {
type: 'bar',
data: howISpendChartdata,
plugins: [ChartDataLabels],
options: {
responsive: true,
maintainAspectRatio: false,
aspectRatio: 2,
plugins: plugins,
scales: scales,
onClick: function (e, activeElements) {
//get the colors for bars
if (activeElements.length > 0) { // check the element is selected
const monthlyChart = config.monthlyChart;
monthlyChart.options.animation.colors = false;
monthlyChart.update();
}
}
}
});
config.monthlyChart.render();
}, 100);
}
}
}
Below is solution for anyone facing similar problem:
options: {
onClick: function (evt, element) {
// get the require data from click event
let chart = Chart.getChart(e.chart.canvas.id);
const points = chart.getElementsAtEventForMode(e, 'nearest', { intersect: true }, true);
if (points.length) {
const firstPoint = points[0];
const elementIndex = firstPoint.index;
const datasetIndex = firstPoint.datasetIndex;
const dataset = chart.data.datasets[datasetIndex];
const datasetFieldLabel = dataset.label;
const itemLabel = chart.data.labels[elementIndex];
const itemValue = dataset.data[elementIndex];
setTimeout(() => {
// destroy the chart
// Render another chart
}, 100);
}
}
}

I build synchronized charts (highcharts) that I want to export in one PDF

Ok so I build sync charts with test data. Everything works perfectly. The only problem I have is that I want to export all of them in one PDF but I only have the option to do it seperatly. So I build in a button that gets the charts in an array and exports it to PDF but it does not want to work.
This is the JS i have that builds the charts
function clickModal(test) {
document.getElementById("myModal").style.display = "block";
// Call the AJAX function that start the chart procedures
getAjaxData(test);
}
// HIGHCHART FUNCTIONALITY STARTS HERE
['mousemove', 'touchmove', 'touchstart'].forEach(function (eventType) {
document.getElementById('container').addEventListener(
eventType,
function (e) {
var chart,
point,
i,
event;
for (i = 0; i < Highcharts.charts.length; i = i + 1) {
chart = Highcharts.charts[i];
// Find coordinates within the chart
event = chart.pointer.normalize(e);
// Get the hovered point
point = chart.series[0].searchPoint(event, true);
if (point) {
point.highlight(e);
}
}
}
);
});
/**
* Override the reset function, we don't need to hide the tooltips and
* crosshairs.
*/
Highcharts.Pointer.prototype.reset = function () {
return undefined;
};
/**
* Highlight a point by showing tooltip, setting hover state and draw crosshair
*/
Highcharts.Point.prototype.highlight = function (event) {
event = this.series.chart.pointer.normalize(event);
this.onMouseOver(); // Show the hover marker
this.series.chart.tooltip.refresh(this); // Show the tooltip
this.series.chart.xAxis[0].drawCrosshair(event, this); // Show the crosshair
};
/**
* Synchronize zooming through the setExtremes event handler.
*/
function syncExtremes(e) {
var thisChart = this.chart;
if (e.trigger !== 'syncExtremes') { // Prevent feedback loop
Highcharts.each(Highcharts.charts, function (chart) {
if (chart !== thisChart) {
if (chart.xAxis[0].setExtremes) { // It is null while updating
chart.xAxis[0].setExtremes(
e.min,
e.max,
undefined,
false,
{ trigger: 'syncExtremes' }
);
}
}
});
}
}
function getAjaxData(test){
$.getJSON('datasync.php', function(chartData, tstSuccess) {
// Display the results of the getJSON call to data.php
document.getElementById("json1").innerHTML = JSON.stringify(tstSuccess, undefined, 2);
document.getElementById("json").innerHTML = JSON.stringify(chartData, undefined, 2);
var charts1 = {}; // global variable
var index = 0;
// Loop through each dataset in the returned JSON
chartData.datasets.forEach(function (dataset, i) {
// Add X values
dataset.data = Highcharts.map(dataset.data, function (val, j) {
return [chartData.xData[j], val];
});
// Create a child div for each dataset that is returned
var chartDiv = document.createElement('div');
chartDiv.className = 'chart';
document.getElementById('container').appendChild(chartDiv);
charts1[index] = Highcharts.chart(chartDiv, {
chart: {
marginLeft: 40, // Keep all charts left aligned
spacingTop: 20,
spacingBottom: 20
},
exporting: {
buttons: {
contextButton: {
menuItems: [
'downloadPDF',
'viewData'
]
}
}
},
title: {
text: dataset.name,
align: 'left',
margin: 0,
x: 30
},
credits: {
enabled: false
},
legend: {
enabled: false
},
xAxis: {
crosshair: true,
events: {
setExtremes: syncExtremes
},
labels: {
//format: '{value} km'
format: ' '
}
},
yAxis: {
title: {
text: null
}
},
tooltip: {
positioner: function () {
return {
// right aligned
x: this.chart.chartWidth - this.label.width - 40,
y: 10 // align to title
};
},
borderWidth: 0,
backgroundColor: 'none',
pointFormat: '{point.y}',
headerFormat: '',
shadow: false,
style: {
fontSize: '18px'
},
valueDecimals: dataset.valueDecimals
},
series: [{
data: dataset.data,
name: dataset.name,
type: dataset.type,
color: Highcharts.getOptions().colors[i],
fillOpacity: 0.3,
tooltip: {
valueSuffix: ' ' + dataset.unit
}
}]
});
});
index++;
});
}
$('#export-pdf').click(function() {
Highcharts.exportCharts([charts1[0], charts1[1]], {
type: 'application/pdf'
});
});
And this is my HTML
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<div id="container">
<button id="export-png">Export to PNG</button>
</div>
</div>
</div>
So im using PHP to build up JSON from an array ( will use SQL to build from database later just want to get the functionality working )
Then I use the highcharts library along with JS to display the charts
Ok so I figured out the problem. I brought in this piece of code
Highcharts.getSVG = function(charts) {
var svgArr = [],
top = 0,
width = 0;
$.each(charts, function(i, chart) {
var svg = chart.getSVG();
svg = svg.replace('<svg', '<g transform="translate(0,' + top + ')" ');
svg = svg.replace('</svg>', '</g>');
svg = svg.replace('-9000000000', '-999'); // Bug in v4.2.6
top += chart.chartHeight;
width = Math.max(width, chart.chartWidth);
svgArr.push(svg);
});
return '<svg height="'+ top +'" width="' + width + '" version="1.1" xmlns="http://www.w3.org/2000/svg">' + svgArr.join('') + '</svg>';
};
/**
* Create a global exportCharts method that takes an array of charts as an argument,
* and exporting options as the second argument
*/
Highcharts.exportCharts = function(charts, options) {
// Merge the options
options = Highcharts.merge(Highcharts.getOptions().exporting, options);
// Post to export server
Highcharts.post(options.url, {
filename: options.filename || 'chart',
type: options.type,
width: options.width,
svg: Highcharts.getSVG(charts)
});
};
I changed the charts so that it does not created an array of chart objects
Highcharts.chart(chartDiv, {
chart: {
marginLeft: 40, // Keep all charts left aligned
spacingTop: 20,
spacingBottom: 20
},
instead of
charts1[index] = Highcharts.chart(chartDiv, {
chart: {
marginLeft: 40, // Keep all charts left aligned
spacingTop: 20,
spacingBottom: 20
},
And in the buttons function I just used the highcharts.charts instead of the array
$('#export-pdf').click(function() {
Highcharts.exportCharts(Highcharts.charts, {
type: 'application/pdf'
});
});

bar chart animation in descending order

I have a PHP search page where union members can check their seniority level. The results page displays their stats along with a chart.js horizontal bar chart showing their seniority level. all works great except the bar animates from the right.
I want the bar to animate from the left, from 397 up to their seniority level.
<script type="text/javascript">
$('#details').on('shown.bs.collapse', function () {
Chart.pluginService.register({
beforeRender: function (chart) {
if (chart.config.options.showAllTooltips) {
// create an array of tooltips
// we can't use the chart tooltip because there is only one tooltip per chart
chart.pluginTooltips = [];
chart.config.data.datasets.forEach(function (dataset, i) {
chart.getDatasetMeta(i).data.forEach(function (sector, j) {
chart.pluginTooltips.push(new Chart.Tooltip({
_chart: chart.chart,
_chartInstance: chart,
_data: chart.data,
_options: chart.options.tooltips,
_active: [sector]
}, chart));
});
});
// turn off normal tooltips
chart.options.tooltips.enabled = false;
}
},
afterDraw: function (chart, easing) {
if (chart.config.options.showAllTooltips) {
// we don't want the permanent tooltips to animate, so don't do anything till the animation runs at least once
if (!chart.allTooltipsOnce) {
if (easing !== 1)
return;
chart.allTooltipsOnce = true;
}
// turn on tooltips
chart.options.tooltips.enabled = true;
Chart.helpers.each(chart.pluginTooltips, function (tooltip) {
tooltip.initialize();
tooltip.update();
// we don't actually need this since we are not animating tooltips
tooltip.pivot();
tooltip.transition(easing).draw();
});
chart.options.tooltips.enabled = false;
}
}
});
Chart.plugins.register({
beforeDraw: function(chartInstance, easing) {
var ctx = chartInstance.chart.ctx;
ctx.fillStyle = 'rgba(89,105,255,.15)'; // your color here
var chartArea = chartInstance.chartArea;
ctx.fillRect(chartArea.left, chartArea.top, chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
}
});
var ctx = document.getElementById("chartjs_bar").getContext('2d');
var data = myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
datasets: [{
backgroundColor: [
"#5969ff",
"#ff407b",
"#25d5f2",
"#ffc750",
"#2ec551",
"#7040fa",
"#ff004e"
],
data:<?php echo json_encode($ChartRank); ?>,
}]
},
options: {
showAllTooltips: true,
tooltips: {
displayColors:false,
custom: function(tooltip) { },
callbacks: {
// use label callback to return the desired label
label: function(tooltipItem, data) {
return "Your Seniority : " + tooltipItem.xLabel;
},
// remove title
title: function(tooltipItem, data) {
return;
}
}
},
title: {
display: true,
padding: 5,
text: 'Seniority level'
},
scales: {
xAxes: [{
display: true,
gridLines: {
display:false,
drawBorder:false
},
ticks: {
reverse:true,
min:1,
stepSize: 50,
max: 397
}
}],
yAxes: [{
display: true,
gridLines: {
display:false,
drawBorder:false
}
}]
},
responsive: true,
legend: {
display:false,
padding:0,
labels: {
fontColor: '#71748d',
fontFamily: 'Circular Std Book',
fontSize: 14,
}
},
}
});
});
</script>

How to display different tooltip based on data values in ChartJS v2?

I’m using ChartJs, to display a Line chart and I’m trying to do 2 things :
The first one is to display different colors based on the tooltip’s value. Highest value vs Medium value
The second one is to display a different tooltip if the tooltips value is the lowest. Minimun value
I’ve tried to use a custom plugins to do this, but It didn’t work
This is the code I've managed to do so far :
Chart.plugins.register({
beforeRender: function(chart) {
if (chart.config.options.showAllTooltips) {
chart.pluginTooltips = [];
chart.config.data.datasets.forEach(function(dataset, i) {
chart.getDatasetMeta(i).data.forEach(function(sector, j) {
console.log(j, sector);
chart.pluginTooltips.push(
new Chart.Tooltip(
{
_chart: chart.chart,
_chartInstance: chart,
_data: chart.data,
_options: chart.options.tooltips,
_active: [sector],
},
chart
)
);
});
});
// turn off normal tooltips
chart.options.tooltips.enabled = false;
}
},
afterDraw: function(chart, easing) {
if (chart.config.options.showAllTooltips) {
if (!chart.allTooltipsOnce) {
if (easing !== 1) return;
chart.allTooltipsOnce = true;
}
// turn on tooltips
chart.options.tooltips.enabled = true;
Chart.helpers.each(chart.pluginTooltips, function(tooltip) {
tooltip.initialize();
tooltip._options.bodyFontFamily = "Visby";
// Change color based on value
tooltip._options.bodyFontColor = '#FEB122';
// Change tooltip's html if minimun value of dataset
// Values .datapoints[0].value
// console.log(tooltip._model);
tooltip._options.displayColors = false;
tooltip._options.bodyFontSize = tooltip._chart.height * 0.05;
tooltip._options.yPadding = 0;
tooltip._options.xPadding = 0;
tooltip.update();
tooltip.pivot();
tooltip.transition(easing).draw();
});
chart.options.tooltips.enabled = false;
}
}
});
let canvas = document.getElementById("myLineChart");
Chart.defaults.global.defaultFontFamily = "Visby";
const ctx = canvas.getContext('2d');
const labels = JSON.parse(ctx.canvas.dataset.dates);
const prices = JSON.parse(ctx.canvas.dataset.prices);
const myLineChart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [{
label: "Prix du billet",
data: prices,
backgroundColor: [
'rgba(0, 0, 0, 0)',
],
borderColor: [
'#F2F2F2',
],
pointBackgroundColor:
'#FEB122',
pointBorderColor:
'#FEB122',
borderWidth: 3,
}]
},
options: {
showAllTooltips: true, // call plugin we created
responsive: true,
cutoutPercentage: 60,
legend: {
position: "bottom"
},
animation: {
animateScale: true,
animateRotate: true
},
tooltips: {
enabled: false,
backgroundColor:"rgba(0,0,0,0)",
callbacks: {
title: function(tooltipItems, data) {
return "";
},
label: function(tooltipItem, data) {
var datasetLabel = "";
var label = data.labels[tooltipItem.index];
return data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index] + '€';
},
labelColor: function(tooltipItem, data) {
// console.log(data);
}
}
},
legend: {
display: false
},
layout: {
padding: {
left: 32,
right: 32,
top: 32,
bottom: 32
}
},
scales: {
xAxes: [{
gridLines: {
display: false,
drawBorder: false,
},
}],
yAxes: [{
display: false
}]
}
}
});
How could I make this work ?
I've managed to do that by using the plugin Chartjs Datalabels.
And using the scriptable colors options.

ChartJS Tooltip position Stacked bar chart

I'm creating a Stacked bar chart. Everything is working as expected except the tooltips. One bar is behind the other one (Kinda like a progress bar) and the problem is that once one bar is getting closer to the other one, the tooltips overlap. So, my question is if I can set "yAlign" position for each data(or each bar) so that I can display the tooltips on the top for one set of bars, and on the bottom to the other set of bars.
Here's my code:
<script>
var ctx = document.getElementById("examples").getContext('2d');
var data = {
labels:[
"A", "B", "C",],
datasets: [{
label: false,
data: [40, 110, 18],
backgroundColor: [
'rgba(255, 99, 132, 0.7)',
'rgba(158, 112, 225, 0.7)',
'rgba(174, 122, 215, 0.7)',
]
},
{
label: false,
data: [100, 200, 50],
backgroundColor: [
'rgb(128,128,128)',
'rgb(128,128,128)',
'rgb(128,128,128)',
]
},
]
};
var currentX = null;
var currentY = null;
var customTooltips = function (tooltip) {
var helpers = Chart.helpers;
var ctx = this._chart.ctx;
var vm = this._view;
if (vm == null || ctx == null || helpers == null || vm.opacity === 0) {
return;
}
var tooltipSize = this.getTooltipSize(vm);
var pt = {
x: vm.x,
y: vm.y
};
if (currentX == vm.x && currentY == vm.y) {
return;
}
currentX = vm.x;
currentY = vm.y;
// IE11/Edge does not like very small opacities, so snap to 0
var opacity = Math.abs(vm.opacity < 1e-3) ? 0 : vm.opacity;
// Draw Background
var bgColor = helpers.color(vm.backgroundColor);
ctx.fillStyle = bgColor.alpha(opacity * bgColor.alpha()).rgbString();
helpers.drawRoundedRectangle(ctx, pt.x, pt.y, tooltipSize.width, tooltipSize.height, vm.cornerRadius);
ctx.fill();
// Draw Caret
this.drawCaret(pt, tooltipSize, opacity);
// Draw Title, Body, and Footer
pt.x += vm.xPadding;
pt.y += vm.yPadding;
// Titles
this.drawTitle(pt, vm, ctx, opacity);
// Body
this.drawBody(pt, vm, ctx, opacity);
// Footer
this.drawFooter(pt, vm, ctx, opacity);
};
Chart.plugins.register({
beforeRender: function (chart) {
if (chart.config.options.showAllTooltips) {
// create an array of tooltips
// we can't use the chart tooltip because there is only one tooltip per chart
chart.pluginTooltips = [];
chart.config.data.datasets.forEach(function (dataset, i) {
chart.getDatasetMeta(i).data.forEach(function (sector, j) {
chart.pluginTooltips.push(new Chart.Tooltip({
_chart: chart.chart,
_chartInstance: chart,
_data: chart.data,
_options: chart.options.tooltips,
_active: [sector]
}, chart));
});
});
// turn off normal tooltips
chart.options.tooltips.enabled = false;
}
},
afterDraw: function (chart, easing) {
if (chart.config.options.showAllTooltips) {
// we don't want the permanent tooltips to animate, so don't do anything till the animation runs atleast once
if (!chart.allTooltipsOnce) {
if (easing !== 1)
return;
chart.allTooltipsOnce = true;
}
// turn on tooltips
chart.options.tooltips.enabled = true;
Chart.helpers.each(chart.pluginTooltips, function (tooltip) {
// This line checks if the item is visible to display the tooltip
if(!tooltip._active[0].hidden){
tooltip.initialize();
// tooltip._options.position = "outer";
// tooltip._options.displayColors = false;
// tooltip._options.bodyFontSize = tooltip._chart.height*0.025;
//tooltip._options.yPadding = tooltip._options.bodyFontSize*0.30;
// tooltip._options.xPadding = tooltip._options.bodyFontSize*0.30;
//tooltip._options.caretSize = tooltip._options.bodyFontSize*0.5;
//tooltip._options.cornerRadius = tooltip._options.bodyFontSize*0.50;
tooltip.update();
// we don't actually need this since we are not animating tooltips
tooltip.pivot();
tooltip.transition(easing).draw();
}
});
chart.options.tooltips.enabled = false;
}
}
})
var myPieChart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
showAllTooltips: true,
legend: {
display: false
},
tooltips: {
titleFontSize: 10,
bodyFontSize: 10,
pointHitDetectionRadius : 3,
yAlign: 'top',
responsive: false,
customTool: customTooltips,
callbacks: {
title: function() {}
},
},
scales:{
xAxes: [{
stacked: true,
ticks: {
beginAtZero: true
},}]
},
}
});
</script>
JSFiddle: https://jsfiddle.net/560gortq/2/

Categories

Resources