Chart.js - Font only renders after you reload the canvas - javascript

I am using Chart.js and I am trying to use a Google Font. The first time I load the page, the chart uses the default font but if I recreate the chart, then the correct font is loaded.
How do I get the font to load the first time the chart is loaded?
My HTML:
<div style="width: 100%;" id="StatsDiv">
<div id="container" style="position: relative; height:300px; width:600px; background-color:#F9F9F9; padding-top:10px;">
<canvas id="myChart" width="600" height="400"></canvas>
</div>
</div>
The loading of the font:
<link href="https://fonts.googleapis.com/css?family=Asap+Condensed:400,500,600" rel="stylesheet" />
The Javascript that does the work:
Chart.defaults.global.defaultFontFamily = 'Asap Condensed';
var myChart = new Chart(document.getElementById("myChart"), {
type: 'bar',
data: {
labels: [FundsLabel,RequestedLabel],
datasets: [
{
label: "Cleared Balance: " + parseFloat(AVBalance).toFixed(2) + " AUD",
backgroundColor: "rgba(98,203,49,0.40)",
borderColor: "rgba(98,203,49,0.75)",
borderWidth: 2,
hoverBackgroundColor: "rgba(98,203,49,0.50)",
hoverBorderColor: "rgba(98,203,49,1.00)",
data: [AVBalance, GreenRequested],
},
{
label: "Pending Balance: " + parseFloat(PDBalance).toFixed(2) + " AUD",
backgroundColor: "rgba(231,76,60,0.40)",
borderColor: "rgba(231,76,60,0.75)",
borderWidth: 2,
hoverBackgroundColor: "rgba(231,76,60,0.50)",
hoverBorderColor: "rgba(231,76,60,1.00)",
data: [PDBalance, RedRequested],
}
]
},
options: {
scales: {
yAxes: [{
stacked: true,
gridLines: {
display: true,
zeroLineColor: '#999999',
zeroLineWidth: '1',
// color: "rgba(255,99,132,0.2)",
color: "rgba(239, 239, 239)",
},
ticks: {
// min: 0, // it is for ignoring negative step.
beginAtZero: true,
fontSize: "12",
// if i use this it always set it '1', which look very awkward if it have high value e.g. '100'.
}
}],
xAxes: [{
stacked: true,
gridLines: {
display: false,
},
barThickness: 120,
scaleLabel: {
display: true,
//labelString: 'Banks'
}
}]
},
maintainAspectRatio: false,
}
});

wrapping the chart rendering code inside document.fonts.ready.then worked for me

The chart won't load your font on the first time because it couldn't find your font (yet). But it works the second time because your font is already cached by browser.
If you want to make sure the font is working, you can do preload the font by using a hidden DOM.
.fontPreloader{
font-family: 'Asap Condensed';
position: fixed;
top: -9999px;
left: -9999px;
}
<div class="fontPreloader">-</div>
<link href="https://fonts.googleapis.com/css?family=Asap+Condensed:400,500,600" rel="stylesheet" />

Waiting for the window to load before creating the chart worked for me:
window.addEventListener('load', function() {
// An example of creating a chart, replace with your code:
var ctx = document.getElementById("myChart").getContext("2d");
var barchart = new Chart(ctx, config);
})

Related

Chart.js colors in bar chart not showing

I've got a chart.js bar chart that renders fine on desktop but on my iPhone the chart bars are black unless I hover over them and then only the WAY bar changes to the correct color.
Code:
<div class="col-sm">
<canvas id="WayChart" width="300" height="300"></canvas> <!-- max-width="100%" -->
<script>
var densityCanvas = document.getElementById("WayChart");
Chart.defaults.global.defaultFontSize = 18;
Chart.defaults.global.defaultFontColor='black';
var controlData = {
label: 'Control',
data: [5.0,4.2,5.6],
backgroundColor: 'rgba(144,18,179)',
borderWidth: 0,
yAxisID: "WAY Depth"
};
var wayData = {
label: 'WAY',
data: [5.3,2.5,2.6],
backgroundColor: 'rgba(0,166,104)',
borderWidth: 0,
yAxisID: "WAY Depth"
};
var daysData = {
labels: ["Day 0", "Day 28", "Day 56"],
datasets: [controlData, wayData],
};
var chartOptions = {
responsive:true,
scales: {
xAxes: [{
barPercentage: 1,
categoryPercentage: 0.5,
ticks: {
fontStyle:'bold'
}
}],
yAxes: [{
id: "WAY Depth",
scaleLabel:{
display:true,
labelString:'Depth (mm)',
fontStyle:'bold',
},
ticks: {
beginAtZero: true
}
}]
},
title:{
display:'true',
text:'Depth Measurements (mm)',
fontSize:18
}
};
var barChart = new Chart(WayChart, {
type: 'bar',
data: daysData,
options: chartOptions
});
</script>
</div>
</div>
Any ideas?
It renders fine in the Chrome phone inspector window but not on my iPhone using FF and Chrome browsers.
I saw the problem right after posting this.
The backgroundColor was written using rgba and needed to be rgb.
Always the little things...

Bar chart legend adjustments - Chart JS

I'm new in Chart JS and I have a bar chart with the legend displayed bellow the chart:
var data = {
labels: [],
datasets: [{
label: 'Disk C',
backgroundColor: "#000080",
data: [80]
}, {
label: 'Disk D',
backgroundColor: "#d3d3d3",
data: [90]
},
{
label: 'Memory',
backgroundColor: "#add8e6",
data: [45]
}]
};
var ctx = document.getElementById("mybarChart");
ctx.height = 300;
var mybarChart = new Chart(ctx, {
type: 'bar',
responsive: true,
data: data,
options: {
legend: {
display: true,
position: 'bottom'
},
scales: {
yAxes: [{
display: false,
ticks: {
beginAtZero: true
},
gridLines: {
color: "rgba(0, 0, 0, 0)",
}
}],
xAxes: [{
display: false,
gridLines: {
color: "rgba(0, 0, 0, 0)",
},
barPercentage: 0.5,
categoryPercentage: 0.5
}]
}
}
});
But the legend should be something like :
It is possible to make the colors rectangles much more smaller and the values to be displayed one below another because in my example the labels are displayed in a single row?
Unfortunately, there is no way to customize the default legend in the manner that you are wanting. Fortunately, however, chart.js thought of this and provided a mechanism for you to generate and style your own legend outside of the canvas object (using regular html/css).
You can use the legendCallback options property to define a method that generates your legend html and then call the chart .generateLegend() prototype method to place into your page. Here is what I mean.
HTML for my page.
<div style="width:25%;">
<canvas id="mybarChart"></canvas>
<div id="legend"></div>
</div>
Then I define how the legend will look in the 'legendCallback' option property.
legendCallback: function(chart) {
var text = [];
text.push('<ul class="' + chart.id + '-legend">');
for (var i = 0; i < chart.data.datasets.length; i++) {
text.push('<li><div class="legendValue"><span style="background-color:' + chart.data.datasets[i].backgroundColor + '"> </span>');
if (chart.data.datasets[i].label) {
text.push('<span class="label">' + chart.data.datasets[i].label + '</span>');
}
text.push('</div></li><div class="clear"></div>');
}
text.push('</ul>');
return text.join('');
}
Finally, I add the legend html to my page.
$('#legend').prepend(mybarChart.generateLegend());
As always, here is a codepen example showing a working solution. You can change your legend look and feel simply by changing the html that is generated by the callback and using css.

ChartJS. Change axis line color

I wanna know if it's possible to change the color of the chart axis using ChartJS.
Thanks
I know this question was asked over 2 years ago and the OP has already marked a correct answer, but I have a solution to the problem that the OP mentioned in the comments of the marked answer and I'd like to solve it to save other people some time.
But this changes the color of the axis and all the gridLines, what if
I just want to change the axis color? For example, I want the axis
line solid black and the grid lines grey.
If you're trying to achieve this, then the marked answer won't do it for you but the following should:
yAxes: [{
gridLines: {
zeroLineColor: '#ffcc33'
}
}]
you can change the color by scales configuration under chart options:
type: '...',
data: {...},
options: {
scales: {
xAxes: [{gridLines: { color: "#131c2b" }}],
yAxes: [{gridLines: { color: "#131c2b" }}]
}
}
Good question and good answer from #A Friend
His answer works perfectly well with ....... chart.js v2.xx
Here now for version 3.xx for those interested:
(as v3.xx is not backwards compatible with v2.xx)
Using borderColor instead of zeroLineColor to change the color of the chart axis using Chart.js v3.xx:
scales: {
x: { // <-- axis is not array anymore, unlike before in v2.x: '[{'
grid: {
color: 'rgba(255,0,0,0.1)',
borderColor: 'red' // <-- this line is answer to initial question
}
},
y: { // <-- axis is not array anymore, unlike before in v2.x: '[{'
grid: {
color: 'rgba(0,255,0,0.1)',
borderColor: 'green' // <-- this line is answer to initial question
}
}
}
Following a working snippet with complete code:
const labels=["2021-08-01","2021-08-02","2021-08-03","2021-08-04","2021-08-05"];
const data_1=[39,41,42,43,43];
const data_2=[37,38,40,41,39];
const ctx=document.querySelector('canvas').getContext('2d');
const data = {
labels: labels,
datasets: [{
label: 'Data 1',
borderColor: 'grey',
data: data_1
}, {
label: 'Data 2',
borderColor: 'grey',
data: data_2
}]
};
const options = {
scales: {
x: {
grid: {
color: 'rgba(255,0,0,0.1)',
borderColor: 'red'
}
},
y: {
grid: {
color: 'rgba(0,255,0,0.1)',
borderColor: 'green'
}
}
}
};
const chart = new Chart(ctx, {
type: 'line',
data: data,
options: options
});
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<!-- gets you the latest version of Chart.js, now at v3.5.0 -->
<canvas width="320" height="240"></canvas>
In the Charjs.JS to style the scale label and ticks we can use below settings.
options: {
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'X axe name',
fontColor:'#000000',
fontSize:10
},
ticks: {
fontColor: "black",
fontSize: 14
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Y axe name',
fontColor: '#000000',
fontSize:10
},
ticks: {
fontColor: "black",
fontSize: 14
}
}]
}
}
Please refer the link for all the properties. Study all the property before implementation.
Happy coding !
For ChartJs 3 updated in 2022
You can pass the options object when initializing the context. In the sample code I was use x to change the line color on X Axis, you can try y as well.
options: {
scales: {
x: {
grid: {
color: '#777777'
}
}
},

Can't Customize Chart.js

I'm very new to Chart.js and I'm working off the bar sample included when downloading Chart.js. I read through the documentation and the sample pages seem to do things a little differently. I tried following the documentation and online tutorials to no success, but working off the sample page is yielding better results.
However I can't seem to customize anything. I'm trying to start the scale value at 0 but it won't apply. This happens to all things I try to do (font color etc. etc. etc. etc.) The rest of the options here were included with the file and work. I'm not sure what I'm doing wrong.
<head>
<title>Bar Chart</title>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="../dist/Chart.bundle.js"></script>
<style>
canvas {
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
</style>
</head>
<body>
<div id="container" style="width: 75%;">
<canvas id="canvas"></canvas>
</div>
<script>
var barChartData = {
labels: ["Week 1", "Week 2"],
datasets: [{
label: 'Round 1',
backgroundColor: "rgba(220,220,220,0.5)",
data: [12,15]
}, {
label: 'Round 2',
backgroundColor: "rgba(151,187,205,0.5)",
data: [20,17]
}]
};
window.onload = function() {
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
scaleOverride:true,
scaleStartValue: 0,
options: {
elements: {
rectangle: {
borderWidth: 2,
borderColor: 'rgb(0, 255, 0)',
borderSkipped: 'bottom'
}
},
responsive: true,
legend: {
position: 'top',
},
title: {
display: true,
text: 'Chart.js Bar Chart'
}
}
});
};
</script>
</body>
You can use tick.beginAtZero
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}],
},
...
Fiddle - http://jsfiddle.net/7mse8p9e/

flot exception invalid dimention for flot height = 0

This is my chart flot options
var chartOptions = {
xaxis: {
min: 0,
max: result.length + 1,
ticks: ticks
},
grid: {
hoverable: true,
clickable: false,
borderWidth: 0
},
bars: {
show: true,
barWidth: 1,
//barWidth:null,
fill: true,
lineWidth: 1,
order: true,
lineWidth: 0,
fillColor: { colors: [{ opacity: 1 }, { opacity: 1 }] }
},
tooltip: true,
tooltipOpts: {
content: '%s: %y'
},
colors: App.chartColors
};
var holder = $('#vertical-chart');
if (holder.length) {
$.plot(holder, data, chartOptions);
}
I got exception:
invalid dimention for flot hieght =0
There is no problem with html because I can draw another chart using the same html
help please
Update
This is the HTML
<div style="width: 45%; height:300px; float: left; margin-left:5%">
<div id="vertical-chart" class="chart-holder" style="border:1px solid #D5D5D5; margin-top:2px">
<canvas class="overlay" width="479" height="265"></canvas>
</div>
</div>
This may fix your problem: Change the canvas class from overlay to flot-overlay.
The class name was changed due to a request here:
https://code.google.com/p/flot/issues/detail?id=540
You'll see the API change described in the second paragraph here:
https://code.google.com/p/flot/source/browse/trunk/NEWS.txt
Without this change, the canvas is being deleted during the plot call, leaving vertical-chart without a height.
If this doesn't fix your problem, it would be useful to see your data object.

Categories

Resources