How to use canvas inside slideshow (chartjs) - javascript

I've been trying to find a working example on how to implement a slideshow that wraps n canvas elements. I attempted to create a very simple slideshow with my canvases based on an example that used list-items with varying backgrounds instead of canvases.
Based on this fiddle I changed the list elements to this:
<div id="slider">
<ul>
<li> <canvas id="programming"> </canvas> </li>
<li> <canvas id="design"> </canvas> </li>
</ul>
</div>
And this is my javascript:
var designBarChartData = {
labels: ["HTML5", "CSS", "jQuery", "JavaScript", "ASP.NET"],
datasets: [{
label: 'Dataset 1',
backgroundColor: ["rgba(255,82,0,1)", "rgba(0,100,255,0.9)", "rgba(255,255,255,0.9)", "rgba(231,131,0, 1)", "rgba(0,122,204,0.8)"],
borderColor: ['rgba(255,39,0,1)', 'rgba(0,20,255, 1)', 'rgba(0,0,0, 1)', 'rgba(232, 90,0, 1)', 'rgba(0,70,204, 1)'],
borderWidth: 3,
yAxisID: "y-axis-1",
data: [40, 30, 50, 40, 30]
}]
};
var langBarChartData = {
labels: ["Core Java", "C/C++", "C#", "Relational-Databases", "VB.NET", "Erlang", "JavaScript"],
datasets: [{
label: 'Programming',
backgroundColor: ["rgba(102,61,0,0.9)", "rgba(5,32,74,0.9)", "rgba(176,0,255,0.8)", "rgba(101,0,0,0.8)", "rgba(0,115,255,0.8)", "rgba(146,0,0,0.9)", "rgba(236,211,0,0.8)"],
yAxisID: "y-axis-1",
data: [40, 30, 50, 40, 60, 20, 30]
}]
};
window.onload = function() {
var ctx = document.getElementById("design").getContext("2d");
window.myBar1 = Chart.Bar(ctx, {
data: designBarChartData,
options: {
responsive: true,
hoverMode: 'label',
hoverAnimationDuration: 400,
stacked: false,
title:{
display:true,
text:"Chart.js Bar Chart - Multi Axis"
},
scales: {
yAxes: [{
type: "linear", // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance
display: true,
position: "left",
id: "y-axis-1",
ticks: {
max: 100,
min: 0
}
}, {
type: "linear", // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance
display: true,
position: "right",
id: "y-axis-2",
gridLines: {
drawOnChartArea: false
}
}],
}
}
});
};
window.onload = function() {
var ctx = document.getElementById("programming").getContext("2d");
window.myBar1 = Chart.Bar(ctx, {
data: langBarChartData,
options: {
responsive: true,
hoverMode: 'label',
hoverAnimationDuration: 400,
stacked: false,
title:{
display:true,
text:"Chart.js Bar Chart - Multi Axis"
},
scales: {
yAxes: [{
type: "linear", // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance
display: true,
position: "left",
id: "y-axis-1",
ticks: {
max: 100,
min: 0
}
}, {
type: "linear", // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance
display: true,
position: "right",
id: "y-axis-2",
gridLines: {
drawOnChartArea: false
}
}],
}
}
});
};
Chart.defaults.global.legend.display = false;
It seems most examples cover slideshows of images, whereas in my case I want to create a slideshow of charts (chartjs - which uses a canvas to draw the chart on).

Related

Chart JS annotation issues

I am trying to load annotation the dynamic chart that I create after receiving data from the database and I have tried all possible options but somehow the chart loads but no the annotations.
chart.js version = v2.9.4
chart-plugin-annotation.min.js version = 0.5.7
Function in JS that runs when data is receiving from db:
function DrawChart(timeLabelList, unitsProducedList, goalList){
if(draw_the_chart != null) draw_the_chart.destroy();
Chart.defaults.global.defaultFontColor = 'white';
var ctx = document.getElementById('draw_the_chart').getContext("2d");
draw_the_chart = new Chart(ctx, {
type: 'line',
//plugins: [ChartAnnotation],
data: {
labels: timeLabelList,
datasets: [
{
label: 'Goal',
yAxisID: 'A',
data: goalList,
//backgroundColor: chartColumnColorBlueSolid,
borderColor: chartColumnColorGreenSolid,
borderWidth: 2,
pointStyle: 'star'
}]
},
options: {
annotation: {
annotations: [
{
id: "a-line-1",
type: "line",
mode: "vertical",
scaleID: "y-axis-0",
value: "1",
borderColor: "red",
borderWidth: 2
}
]
},
legend: {
position: 'bottom',
display: true,
},
elements: {
line: {
tension: 0
}
},
scales: {
xAxes: [{
stacked: true,
type: 'time',
time: {
unit: 'hour'
},
}],
yAxes: [{
stacked: false,
id: 'A',
type: 'linear',
position: 'right',
}]
},
}
});
}
I tried all possible ways to register and also different ways to used the plugin but had no luck plotting it. I even used latest CDN versions but had no luck.
Can anyone help with it.
Thanks!

chartjs-plugin-streaming: onRefresh() callback isn't working

Hello I'm new in javascript world; I'm trying to display random numbers in real time with Chart.js and chartjs-plugin-streaming starting from a tutorial code which I started to modify for my scope.
const Chart= require ("chart.js");
const chartStreaming = require('chartjs-plugin-streaming');
const boxWhiteColor = "#2043CE";
const pressure_graph = document.getElementById('pressureGraph').getContext('2d');
Chart.register(chartStreaming);
let pressure_graph_config = {
type: 'line',
data: {
datasets: [{
label: 'Pressure',
data: [],
borderColor: boxWhiteColor,
fill: false
}]
},
options: {
title: {
display: true,
text: 'PRESSURE',
fontColor: boxWhiteColor,
fontSize: 30
},
scales: {
xAxes: [{
gridLines: {
display: true,
drawBorder: true,
color: boxWhiteColor,
lineWidth: 5},
ticks: {
fontColor: boxWhiteColor,
display: false
},
type: 'realtime',
realtime: {
duration: 10000,
refresh: 100, // plot at 10 Hz
delay:200,
pause: false, // chart is not paused
ttl: undefined, // data will be automatically deleted as it disappears off the chart
frameRate: 100, // data points are drawn 100 times every second
onRefresh: chart => {
console.log(trocarP.data.datasets.data);
chart.config.data.datasets.forEach(function(dataset) {
chart.data.dataset[0].data.push({
x: Date.now(),
y: Math.random() //pressure16bits[pressure16bits.length-1]
});
});
}
}
}],
yAxes: [{
scaleLabel: {
display: true,
labelString: '[mmHg]', fontColor: boxWhiteColor, fontSize: 30, fontStyle: 900,
},
ticks: {
fontColor: boxWhiteColor,
fontSize: 25,
fontStyle: 700,
maxTicksLimit: 5,
min: 0,
max: 40,
},
gridLines: {display: true, drawBorder: true, color: boxWhiteColor, lineWidth: 5},
}]
},
elements: {
point: {radius: 0},
},
legend: { display: false}
}
}
trocarP = new Chart (pressure_graph, pressure_graph_config);
The problem is the graph is being created on a canvas via the .html file, but then it doesn't display anything; trying to debug the code I found out that the console.log() I placed inside the onRefresh callback is not printing anything, so I'm assuming the callback isn't working. Any clue on what's happening?
Screenshot of the graph
Edit: I noticed that also Y axis label has not been displayed. I don't get what's wrong with this code.
You are using v2 syntax while using v3 of the lib this wont work as there are several breaking changes, see migration guide for all of them.
For example, way of defining scales has changed, you need an adapter for dates and more.
working basic v3 example:
var options = {
type: 'line',
data: {
datasets: [{
label: '# of Votes',
data: [],
borderColor: 'pink'
}]
},
options: {
scales: {
x: {
type: 'realtime',
realtime: {
duration: 20000,
refresh: 100,
delay: 200,
onRefresh: chart => {
const now = Date.now();
chart.data.datasets.forEach(dataset => {
dataset.data.push({
x: now,
y: Math.random()
});
});
}
}
}
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-streaming/2.0.0/chartjs-plugin-streaming.js"></script>
</body>

How to display grid lines (without showing label) between each ticks?

I'm using Chart.js 2 (React-chart-js 2) to display a line chart.
Does anyone have any reference to keeping the vertical gridline between each displayed label?
It seems like the vertical gridline only showing on each displayed label.
You can make use of the scriptable options for this, see example that hides every second label, you can adjust it to hide a bigger step if you want.
Example:
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderWidth: 1
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderWidth: 1
}
]
},
options: {
scales: {
x: {
ticks: {
callback: function(val, index) {
return index % 2 === 0 ? this.getLabelForValue(val) : '';
}
}
}
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.0.0/chart.js"></script>
</body>
You can try using following configuration
var config = {
type: 'line',
showDatapoints: true,
legend: { position: 'top' },
data: data,
options: {
responsive: true,
hoverMode: 'index',
stacked: false,
title: {
display: true,
text: 'Chart Title'
},
scales: {
yAxes: [{
type: 'linear', // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance
display: true,
position: 'left',
id: 'y-axis-1',
},
{
type: 'linear', // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance
display: true,
position: 'right',
id: 'y-axis-2',
// grid line settings
gridLines: {
drawOnChartArea: true, // only want the grid lines for one axis to show up
},
}],
}
}
};

Chart.js Stacked Bar - datasets visibility and ordering

I have a stacked chart with 3 datasets: Red, Green, Blue.
Here is the link to JSFiddle: https://jsfiddle.net/bwcfL58v/
Let's imagine that these are the layers, which overlay each others:
Red as bottom layer, then Green as middle layer and Blue as top layer.
Take a look at the third day: we don't see the red value, cause it behind the green value (red smaller than green here). So, the question is how to move Green to the bottom layer and Red higher. I need the biggest value to be always at the bottom and the smallest value - at the top, this will allow us to see all the datasets for each day.
All I need is to datasets always be visible and do not hide each others.
let ctx = document.getElementById("myChart");
let myChart = new Chart(ctx, {
type: "bar",
data: {
labels: ["Day 1", "Day 2", "Day 3"],
datasets: [
{
label: 'Blueberry',
data: [25, 30, 40],
backgroundColor: 'blue',
},
{
label: 'Greenberry',
data: [50, 60, 100],
backgroundColor: 'green',
},
{
label: 'Strawberry',
data: [100, 120, 50],
backgroundColor: 'red',
}
]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
xAxes: [{
stacked: true,
gridLines: {
drawOnChartArea: false
},
}],
yAxes: [{
stacked: false,
display: false,
gridLines: {
drawOnChartArea: false
},
ticks: {
beginAtZero: true,
},
}]
},
legend: {
display: false
}
}
});

Chart.js: Minimum value for x-axis at horizontal stacked bar chart

I am using Chart.js to generate a horizontal stacked bar chart. The chart currently looks like this:
This chart shows the user after how many years they should restorate a specific component of a house. I am trying to change this to in which year the user should do the restoration. Adding the current year to the values results to the following:
This is pretty much what I need if I could set the starting value of the x-axis to the current year. I tried to do this setting the minimum value like this:
options: {
scales: {
xAxes: [{
ticks: {
min: 2017
},
...
Unfortunatly results in not displaying the datasets at all like this:
I tried all combinations with adding the current year and setting the minimum values but nothing results in a useful chart.
In the following you can see my current source code:
var mainChart_ctx = document.getElementById("main_chart").getContext("2d");
var mainChart_config = {
type: 'horizontalBar',
data: {
labels: ['Kellerdecke', 'Fenster', 'Außenwand', 'Erdberührter Boden', 'Dach'],
datasets: [{
label: 'Beginn ab heute',
backgroundColor: 'transparent',
data: [4, 21, 25, 25, 25],
borderColor: '#666',
borderWidth: 1
},
{
label: 'Sanierungsdauer',
backgroundColor: '#ffcc00',
data: [2, 5, 5, 5, 5],
borderColor: '#666',
borderWidth: 1
},
{
label: 'Mittlere Restlebensdauer',
backgroundColor: 'orange',
data: [39, 0, 38, 51, 37],
borderColor: '#666',
borderWidth: 1
},
{
label: 'Maximale Restlebensdauer',
backgroundColor: 'orangered',
data: [20, 0, 0, 0, 0],
borderColor: '#666',
borderWidth: 1
}
]
},
options: {
tooltips: {
enabled: true
},
legend: {
display: false
},
title: {
display: true,
text: 'Sanierungsfahrplan',
fontSize: 24
},
scales: {
xAxes: [{
ticks: {
min: 0 /* Todo: change to current year? */
},
stacked: true,
scaleLabel: {
display: true,
labelString: 'Jahre',
fontSize: 16
}
}],
yAxes: [{
ticks: {
stepSize: 10
},
stacked: false,
scaleLabel: {
display: true,
labelString: 'Bauteil',
fontSize: 16
},
}]
}
}
};
mainChart = new Chart(mainChart_ctx, mainChart_config)
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.bundle.min.js"></script>
<canvas id="main_chart"></canvas>
I was able to get a suitable result using a callback like this:
xAxes: [{
ticks: {
min: 0,
callback: function (value, index, values) {
return value + 2017;
}
},
...
]
I found that suggestedMin works well:
options: {
scales: {
xAxes: [{
display: true,
ticks: {
suggestedMin: 2017
}
}]
}
}

Categories