Posted 2/28/2022
Line Graph
A simple canvas implementation of a 2-d line graph
Source Code
This is the first of a series of postings demonstrating basic JavaScript implementations of charts and graphs. Imalgam is creating visualization tools to aid with projects under development, and some of the results will be shared here.
Below are sample renderings using the LineGraph JavaScript class. In the first case (Square Root), the data source is a list of (x, y) values, and in the second case (Sine function) the data source is a JavaScript lambda function characterizing the values of y as a function of x.
Square Root
    const data = [];
    for (let i = 0; i < 200; i++) {
        data.push([i/20.0, Math.pow(i/20.0,0.5)]);
    new LineGraph(
        {"title": "y = f(x) = Math.pow(x, 0.5)",
         "legend": {"x": "X value", "y": "Y value"},
         "data": data
Sine function
    new LineGraph(
        {"title": "y = f(x) = Math.sin(x)",
        "legend": {"x": "X value", "y": "Y value"},
        "dataFunction": a => Math.sin(a),
        "min": 0.0,
        "max": 9.0
The LineGraph class has two externally consumed methods, the constructor and renderTo. The constructor takes as its argument the graph's configuration, described in detail below. The renderTo method takes as its argument a canvas object in the DOM where the graph is rendered. The constructor does not copy/clone the configuration object, so that any changes to the configuration object passed to the constructor will affect the rendering if said change is made before calling renderTo.
LineGraph configuration Object
[Optional] Title of the chart, displayed centered at the top of the chart.
[Optional] Legend Object.
[Optional] Array whose elements are two-entry Arrays representing points to be rendered. The two-entry arrays are of the form [x-value, y-value]. data is optional, it ought not be present if dataFunction is provided.
[Optional] A function which when passed a x-value returns the associated y-value for the rendered graph. dataFunction is optional, and overrides data if it is also present.
[Optional] Minimum x-value of the graph, if dataFunction is provided.
[Optional] Maximum x-value of the graph, if dataFunction is provided.
Legend Object
[Optional] Label of the x-axis.
[Optional] Label of the y-axis.
Imalgam © 2022