Диаграмма JS настраиваемая подсказка?
Я пытаюсь построить диаграмму, используя Chart.Js. Этот chart.js имеет параметр по умолчанию для всплывающей подсказки, я хочу сделать настраиваемую подсказку. Есть ли способ сделать это возможным?
Вот мой код
var chart = null;
barChart: function (data1, data2, data3, label) {
var data = {
labels: label,
datasets: [
{
fillColor: "rgba(220,220,220,0.5)",
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data: data1
},
{
fillColor: "rgba(151,187,205,0.5)",
strokeColor: "rgba(151,187,205,0.8)",
highlightFill: "rgba(151,187,205,0.75)",
highlightStroke: "rgba(151,187,205,1)",
data: data2
},
{
fillColor: "rgba(0,255,0,0.3)",
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(0,255,0,0.3)",
data: data3
},
]
}
var cht = document.getElementById('exampleCanvas');
var ctx = cht.getContext('2d');
if (chart)
chart.destroy();
chart = new Chart(ctx).Bar(data);
}
Ответы
Ответ 1
Попробуйте следующее:
Вы можете вносить изменения во всем мире с помощью этого кода:
Chart.defaults.global = {
// Boolean - Determines whether to draw tooltips on the canvas or not
showTooltips: true,
// Array - Array of string names to attach tooltip events
tooltipEvents: ["mousemove", "touchstart", "touchmove"],
// String - Tooltip background colour
tooltipFillColor: "rgba(0,0,0,0.8)",
// String - Tooltip label font declaration for the scale label
tooltipFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
// Number - Tooltip label font size in pixels
tooltipFontSize: 14,
// String - Tooltip font weight style
tooltipFontStyle: "normal",
// String - Tooltip label font colour
tooltipFontColor: "#fff",
// String - Tooltip title font declaration for the scale label
tooltipTitleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
// Number - Tooltip title font size in pixels
tooltipTitleFontSize: 14,
// String - Tooltip title font weight style
tooltipTitleFontStyle: "bold",
// String - Tooltip title font colour
tooltipTitleFontColor: "#fff",
// Number - pixel width of padding around tooltip text
tooltipYPadding: 6,
// Number - pixel width of padding around tooltip text
tooltipXPadding: 6,
// Number - Size of the caret on the tooltip
tooltipCaretSize: 8,
// Number - Pixel radius of the tooltip border
tooltipCornerRadius: 6,
// Number - Pixel offset from point x to tooltip edge
tooltipXOffset: 10,
// String - Template string for single tooltips
tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %>",
// String - Template string for single tooltips
multiTooltipTemplate: "<%= value %>",
// Function - Will fire on animation progression.
onAnimationProgress: function(){},
// Function - Will fire on animation completion.
onAnimationComplete: function(){}
}
Используйте Ссылка для справки
Ответ 2
Это очень просто, когда вы знаете, где поставить эту опцию.
Ответ заключается в том, чтобы добавить настраиваемый параметр при создании диаграммы:
chart = new Chart(ctx).Bar(data, {"options goes here"} );
После передачи переменной данных с информацией о данных вы можете добавить настраиваемые параметры, поэтому, например, вы хотите изменить размер заголовка всплывающей подсказки, а также хотите поместить светлый серый цвет в заголовок всплывающей подсказки вы бы сделали что-то подобное:
chart = new Chart(ctx).Bar(data, {
//Option for title font size in pixels
tooltipTitleFontSize: 14,
//Option for tooltip title color
tooltipTitleFontColor: "#eee",
});
Другой способ, который вы можете сделать, - создать набор параметров в качестве переменной для организационных целей и иметь возможность повторно использовать его.
//Create a set of relevant options for you chart
var myoptions = {
scaleShowGridLines : false,
responsive : true,
scaleFontSize: 12,
pointDotRadius : 4,
scaleFontStyle: 14,
scaleLabel: "<%= ' ' + value%> %",
}
//Create the Chart
chart = new Chart(ctx).Bar(data, myoptions);
Надеюсь, теперь ясно.
Привет
Ответ 3
Я использовал это, я нашел его в stackoverflow, но я не могу найти его снова
<div id="chartjs-tooltip"></div>
var chartoptions =
{
customTooltips: function ( tooltip )
{
var tooltipEl = $( "#chartjs-tooltip" );
if ( !tooltip )
{
tooltipEl.css( {
opacity: 0
} );
return;
}
tooltipEl.removeClass( 'above below' );
tooltipEl.addClass( tooltip.yAlign );
// split out the label and value and make your own tooltip here
var parts = tooltip.text.split( ":" );
var innerHtml = '<span>' + parts[0].trim() + '</span> : <span><b>' + parts[1].trim() + '</b></span>';
tooltipEl.html( innerHtml );
tooltipEl.css( {
opacity: 1,
left: tooltip.chart.canvas.offsetLeft + tooltip.x + 'px',
top: tooltip.chart.canvas.offsetTop + tooltip.y + 'px',
fontFamily: tooltip.fontFamily,
fontSize: tooltip.fontSize,
fontStyle: tooltip.fontStyle
} );
}
}
Ссылка на то, где я получил его: Chart.js: изменение шаблона подсказки
Ответ 4
Вы можете проверить tooltip css - http://www.chartjs.org/docs/#chart-configuration-tooltip-configuration
tooltips:
{
bodyFontColor: "#000000", //#000000
bodyFontSize: 50,
bodyFontStyle: "bold",
bodyFontColor: '#FFFFFF',
bodyFontFamily: "'Helvetica', 'Arial', sans-serif",
footerFontSize: 50,
callbacks: {
label: function(tooltipItem, data) {
var value = data.datasets[0].data[tooltipItem.index];
if(tooltipItem.index == 0) {
return "<?php echo $data1;?>";
}
else if(tooltipItem.index == 1) {
return "<?php echo $data2;?>";
}
else if(tooltipItem.index == 2) {
return "<?php echo $data3;?>";
}
else {
return "<?php echo $data4; ?>";
}
},
},
},
Ответ 5
Новая версия chart.js, версия 2, находится здесь:
https://github.com/nnnick/Chart.js/releases
Версия 2 добавляет tooltip callbacks
:
Каждый обратный вызов tooltip (beforeTitle, title, afterTitle и т.д.) принимает строку или массив. Если используется массив, он будет создавать несколько строк. Теперь всплывающие подсказки имеют гораздо больше возможностей для визуальной настройки.
Однако имеется вилка chart.js, называемая chartNew.js, найденная здесь:
https://github.com/FVANCOP/ChartNew.js/
Он добавляет несколько замечательных улучшений для почтенного chart.js, включая:
-
функции подсказки (при загрузке/распаковке, посмотрите в папке Samples
и посмотрите annotateFunction.html
. При наведении курсора на любую точку вы можете сделать что угодно.)
-
передача массива цветов на гистограмму (вместо каждого ряда последовательно одного цвета)
-
размещение текста на диаграмме везде, где вы хотите.
много и т.д.
Обратите внимание, что chart.js значительно улучшилось в версии 2, но новая версия не полностью обратная совместимость (просто переход к плагину v2 нарушил мой существующий код), тогда как chartNew.js будет работать со старым кодом, расширяя возможности.
Ответ 6
Я нашел эту страницу полезной:
https://github.com/nnnick/Chart.js/blob/master/samples/pie-customTooltips.html
Он показывает, где и как определить функцию для вашей специальной всплывающей подсказки, а также пример стиля.
Мне пришлось изменить код в соответствии с моими потребностями, но это отличный пример того, как реализовать пользовательскую подсказку.
Некоторые вещи, которые следует отметить, сначала отбросили меня:
1) Идентификатор в правилах стиля должен быть изменен в соответствии с вашей подсказкой div. (это очевидно, но я не поймал его сначала)
2) tooltip.text будет следовать формату, указанному в параметрах tooltipTemplate, или по умолчанию tooltipTemplate, заданному в chart.js
Ответ 7
может быть, это может помочь вам
Chart.types.Line.extend({
name: "LineAlt",
initialize: function (data) {
Chart.types.Line.prototype.initialize.apply(this, arguments);
var xLabels = this.scale.xLabels
xLabels.forEach(function (label, i) {
if (i % 2 == 1)
xLabels[i] = label.substring(1, 4);
})
}
});
var data = {
labels: ["1/jan/08", "15/fab/08", "1/mar/08", "1/apr/08", "10/apr/08", "10/may/2008", "1/jun/2008"],
datasets: [{
label: "First dataset",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,20,20,1)",
pointColor: "rgba(220,20,20,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [65, 59, 80, 81, 56, 55, 90]
}, {
label: "Third dataset",
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(15,187,25,1)",
pointColor: "rgba(15,187,25,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
data: [38, 55, 50, 65, 35, 67, 54]
}]
};
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx).LineAlt(data);
// Chart.js replaces the base inRange function for Line points with a function that checks only the x coordinate
// we replace it with the original inRange fucntion (one that checks both x and y coordinates)
myChart.datasets.forEach(function(dataset) {
dataset.points.forEach(function(point) {
point.inRange = Chart.Point.prototype.inRange;
});
});
// Chart.js shows a multiTooltip based on the index if it detects that there are more than one datasets
// we override it to show a single tooltip for the inRange element
myChart.showTooltip = function(ChartElements, forceRedraw) {
// this clears out the existing canvas - the actual Chart.js library code is a bit more optimized with checks for whether active points have changed, etc.
this.draw();
// draw tooltip for active elements (if there is one)
Chart.helpers.each(ChartElements, function(Element) {
var tooltipPosition = Element.tooltipPosition();
new Chart.Tooltip({
x: Math.round(tooltipPosition.x),
y: Math.round(tooltipPosition.y),
xPadding: this.options.tooltipXPadding,
yPadding: this.options.tooltipYPadding,
fillColor: this.options.tooltipFillColor,
textColor: this.options.tooltipFontColor,
fontFamily: this.options.tooltipFontFamily,
fontStyle: this.options.tooltipFontStyle,
fontSize: this.options.tooltipFontSize,
caretHeight: this.options.tooltipCaretSize,
cornerRadius: this.options.tooltipCornerRadius,
text: Chart.helpers.template(this.options.tooltipTemplate, Element),
chart: this.chart,
custom: this.options.customTooltips
}).draw();
}, this);
};
http://jsfiddle.net/6cgo4opg/747/