JSFiddle - React, Tailwind, and code Playground

by mflodin

HTML

<canvas id="graphSpace" width="700" height="500"></canvas>

JavaScript

// drawLine - draws a line on a canvas context from the start point to the end point 


function drawLine(contextO, startx, starty, endx, endy) {
    contextO.beginPath();
    // Since we use a line width of 1px we shift the line by 0.5px to avoid aliasing
    contextO.moveTo(startx - 0.5, starty + 0.5);
    contextO.lineTo(endx - 0.5, endy + 0.5);
    //contextO.moveTo(startx, starty);
    //contextO.lineTo(endx, endy);          
    contextO.closePath();
    contextO.stroke();
}

// drawRectangle - draws a rectangle on a canvas context using the dimensions specified


function drawRectangle(contextO, x, y, w, h, fill) {
    contextO.beginPath();
    contextO.rect(x - 0.5, y + 0.5, w, h);
    //contextO.rect(x, y, w, h);
    contextO.closePath();
    contextO.stroke();
    if (fill) {
        contextO.fill();
    }
}

function drawBarChart(context, data, maxBarWidth, numMarkersY) {
    // Draw the x and y axes
    context.lineWidth = "1.0";
    var dataCount = Object.keys(data).length;
    var chartHeight = context.canvas.height - 100; // - margin for the bottom labels
    var minY = 10; // margin for top labels
    var startY = chartHeight + minY;
    var startX = 40; // margin for Y axis labels
    // TODO: calculate all margins from label lengths
    var chartWidth = context.canvas.width - startX;
    var barWidth = Math.min(maxBarWidth, chartWidth / dataCount);

    var maxValue = 1;
    for (var d in data) {
        if (data[d] > maxValue) {
            maxValue = data[d];
        }
    }

    var i = 0;
    for (var d in data) {
        if (data.hasOwnProperty(d)) {
            // Extract the data
            var name = d;
            // Normalize to largest value
            var height = ((chartHeight) / maxValue) * data[d];


            // Write the data to the chart
            context.fillStyle = "#06f";
            drawRectangle(context, startX + (i * barWidth), (startY - height), barWidth, height, true);

            // Label setup
           ...