So there is more that one way to make charts with canvas of course. In this post I am using a project called chart js that is pretty flashy, but it is also not to hard to just work out a chart with just the canvas 2d drawing context by itself. So a canvas chart could be created by adding chartjs to a project, or it could be just created with methods like line to, move to, and stroke when just working with the plain old canvas 2d drawing context.
So to get started with chartjs first I need to grab the version of chartjs that I want to use. In this post I was using chartjs 2.7.1. Once I have a copy of chartjs to link to with a script tag I can then write some code for a basic line chart.
Updating a chart is as simple as just changing the dataset values and calling the chart.update method in the instance of Chart that is returned when calling the constructor.
I have a self executing function expression that returns the method that will be used to draw the line chart and inside the body of the closure I have a single helper function worked out that sets the scale of the data based on the height of the canvas. In addition the width of the canvas stipulates the delta x value that will process of each item in the data set.
So here I have an html file example in which I am using the draw line chart method that I worked out.
The project works as expected, but there is a bit more that comes to mind. I might want better control over the location and size of the area where the line chart will be placed in the canvas for example. In addition I would also want to add some labeling for the scale and a legend. However there is still only so much more that comes to mind and it still fulfills the most important aspect of such a project.
Chart.js is pretty cool for doing anything with charts. I just wanted to put together a quick post on this one, I will likely write more about it in the future.