Im facing problem right now which I cant solve by myself after hours of digging.
Im drawing chart using chart js library. Dataset is provided by client via text input field with oninput action. Oninput actions run function which is doing some maths, prepares dataset and updates chart. It is working perfect. But I need also draw a custom text (based on provided data) on chart canvas. Text is visible on canvas, but after user inputs some data, update removes that custom text (what is pretty logic). Cant figure it out how could I deal with it.
HTML file:
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/chart.js" type="text/javascript"></script>
<script src="js/someMaths.js" type="text/javascript"></script>
</head>
<body>
<input type="text" id="progress" oninput="someMaths()">
<canvas id="testChart"></canvas>
</body>
<script src="js/myChart.js" type="text/javascript"></script>
</html>
someMaths.js
function someMaths() {
// reading inputs value and doing some maths, preparing datasets, than...
pushData(newDatasets);
}
function pushData(newDatasets) {
let i = 0;
chart.data.datasets.forEach((dataset) => {
dataset.data = newDatasets[i];
i++;
});
chart.update();
// I was trying here, after update to run function with canvas.fillText(), but it didnt worked
}
and myChart.js
let canvas = document.getElementById('testChart').getContext('2d');
const data = {
datasets: [{
// some options
}, {
// some options
}, {
// some options
}]
}
const options = {
type: 'line',
data: data,
options: {
// some options
}
}
let chart = new Chart(canvas, options);
This is how its constructed, castrated from code that doesnt matter here. It works as intended until I want to draw text on canvas after every single update.
No idea how to achieve it.
Thanks for help!
>Solution :
You will need to use the plugin system, this will make it so you always can draw on the canvas in the right time without it being wiped
var ctx = document.getElementById("chart").getContext("2d");
var myLine = new Chart(ctx, {
type: 'line',
data: {
labels: ["label1", "label2", "label3", "label4"],
datasets: [{
label: 'Demo',
data: [-2, -3, 4, 6],
}]
},
options: {},
plugins: [{
id: 'customText',
afterDraw: (chart) => {
chart.ctx.fillText("Hello World!", 30, 50);
}
}]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.2.0/chart.umd.js"></script>
<canvas id="chart"></canvas>