With CanvasJS, you can create and add dataPoints from user input.
For creating basic Chart, please refer to getting started. In this tutorial, we will cover how to create charts from dataPoints from user input.
Here are the steps for creating Chart from user input:
Create a basic chart as usual. But, we will assign dataPoints to a pre-defined variable (dps in this example). Initially, we will take dps as an empty array and later on add dataPoints to it from user input.
var dps = []; //dataPoints. var chart = new CanvasJS.Chart("chartContainer",{ title :{ text: "Accepting DataPoints from User Input" }, data: [{ type: "line", dataPoints : dps }] });
Now, in order to accept dataPoints from user input, we just need to check the user-input, push it to dps and call chart.render() again. To perform these we will write a addDataPointsAndRender method.
HTML:
X Value:<input id="xValue" type="number" step="any" placeholder="Enter X-Value"> Y Value:<input id="yValue" type="number" step="any" placeholder="Enter Y-Value"> <button id="renderButton">Add DataPoints & Render Chart</button>
Each time the updateChart method is called, a new dataPoint is added and chart is rendered again.
JavaScript:
function addDataPointsAndRender() { xValue = Number(document.getElementById('xValue').value); yValue = Number(document.getElementById('yValue').value); dps.push({ x: xValue, y: yValue }); chart.render(); } var renderButton = document.getElementById('renderButton'); renderButton.addEventListener('click', addDPsAndRender);
To summarize, in order to create chart with dataPoints from user input, you should update dataPoints whenever input is given and call chart.render()
Below is the compilation of final code.