Introduction
Charts had become a normal part of our lives, visual elements of our work. How do they grow? Are they decreasing or increasing? Or just to see progress over time.
So it hits me. Why not create a chart-building webpage where you enter the data and it creates the webpage? And with the help of AI it could be even easier.
What's the idea?
Easy, it should:
- Let me enter data.
- See the progress over time.
- And finally download it as a PNG.
But what it really needs is the code?
First part: CSS
- Styles the layout (dark theme, spacing, and buttons).
- Makes the interface clean and readable.
Javascript
Main function
function drawChart() { ... }
This function is the heart of the code. It lets you read the input, draw a grid, and last but not least, plot data.
Receiving the user input
const vMin = parseFloat(document.getElementById("vMin".value);
This part is used to take the inputs and convert them into numbers. With this part the code will not know what to draw. So basically it's useless.
Setting up the canvas
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
Everything you see on the chart is drawn here. So basically it creates the drawing board.
Grid drawing
ctx.moveTo(pad, y);
ctx.lineTo(pad+w, y);
ctx.stroke();
For creating the vertical and horizontal lines, the squares in the background.
Scaling the data
let normalized = (val - vMin) / (vMax - vMin);
Now this line is very important. It converts the data into percentages. And make them fit inside the chart.
Positioning each point at the right place
let x = pad + (i/(data.length-1)) * w;
let y = pad + h - normalized * h;
- spreads points across X
- places them correctly on Y
Drawing the data lines (of your data)
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x, y);
ctx.stroke();
Without this, the image will appear as just squares and no data inside them.
Download image
canvas.toDataURL()
This part is what lets the image be downloaded.
Here's a demo if you want to try it yourself.
Who it can be used for
Today, every company uses graphs. And even people, when they want to show things to other people. They can make it into graphs, so they are more readable.
Even in schools and universities, they teach students about graphs and how to use them.
Conclusion
This idea is basically a way to make showing data easier. And to see that with a little bit of coding and imagination, it could become possible.
Coding isn't just about writing code. But about what the code does. It is the most important part.
