bar chart banner

Build Simple Bar Charts with HTML, CSS & JavaScript (No Libraries!)

Data visualization plays a crucial role in conveying information clearly and effectively. Often, complex data sets become easier to understand when presented visually. Among various visualization techniques, bar charts excel at displaying comparisons between different categories or showcasing trends over time.

This tutorial is specifically designed for beginners who want to take their first steps in creating basic bar charts using HTML, CSS, and JavaScript. No prior experience with external libraries is required. We will guide you through the process step-by-step, empowering you to craft customizable and interactive bar charts using the power of the canvas element.

Objectives

By the end of this tutorial, you will have gained a solid understanding of:

  • The fundamental building blocks of a bar chart using HTML.
  • Essential CSS styling techniques for visual presentation.
  • JavaScript logic for dynamically generating and manipulating the bar chart within the canvas element.

Now let's unlock the potential of canvas-based bar charts and add a valuable skill to your web development toolkit!

Prerequisites

To get the most out of this tutorial, you'll need a basic grasp of:

  • HTML: How to structure a webpage using elements like <div> and <canvas>.
  • CSS: How to style elements with properties like <width>, <height>, and <background-color>.
  • JavaScript: Understanding concepts like <variables>, <functions>, and how to manipulate elements of a webpage.

Setting Up the HTML Structure

HTML
                        
<div id="chart-container">
    <canvas id="myChart"></canvas>
</div>

We begin with a <div> element with the ID "chart-container." This container serves as a wrapper for the actual chart, providing a designated area for its placement and potential future styling.

Inside the container, we embed a <canvas> element with the ID "myChart." This is the core element where the bar chart will be drawn using JavaScript.

Styling the Chart with CSS

CSS
                        
body {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}

#chart-container {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px;
    width: fit-content;
    height: fit-content;
    border: 2px dashed grey;
    background-color: rgba(255, 235, 205, 0.519);
    margin: auto;
}

Body:

  • Layout: We use display: flex; to arrange content horizontally, then center it both vertically and horizontally within the viewport using justify-content: center; and align-items: center;. This ensures the chart occupies the central area of the screen.
  • Full Height: The body height is set to 100% of the viewport using height: 100vh;, making the chart visible regardless of the page content's length.

Chart Container:

  • Flexible Alignment: display: flex; enables flexible box layout for the container, allowing for easy centering of the chart within it.
  • Centering: We center the chart both vertically and horizontally within the container using align-items: center; and justify-content: center;.
  • Padding (breathing room): We add a 20-pixel padding around the chart using padding: 20px; to create space between the chart and the container's borders, enhancing visual clarity.
  • Automatic Sizing: width: fit-content; and height: fit-content; ensure the container automatically adjusts its size to perfectly fit the chart, avoiding unnecessary space.
  • Visual Definition: A dashed grey border with a thickness of 2 pixels is applied using border: 2px dashed grey; to visually distinguish the chart area from the rest of the page.
  • Subtle Background: A semi-transparent light yellow background with the color code rgba(255, 235, 205, 0.519); is set using background-color: to provide a subtle visual separation for the chart.
  • Auto Centering: margin: auto; sets margins for the container to automatically center it within its parent element, ensuring proper placement on the page.

Creating the Chart Logic with JavaScript

JAVASCRIPT
                        
// Get references to the canvas and its context
const canvas = document.getElementById("myChart");
const ctx = canvas.getContext("2d");

// Sample data
const salesData = [
    { date: "Jan", sales: 15 + 10 },
    { date: "Feb", sales: 23 + 15 },
    { date: "Mar", sales: 18 + 20 },
    { date: "Apr", sales: 25 + 25 },
    { date: "May", sales: 20 + 20 }
];

const barColors = ["red", "orange", "yellow", "lime", "blue"];

// Calculate dimensions for the chart
const barWidth = 50;
const barGap = 10;
const numBars = salesData.length;
const chartWidth = numBars * (barWidth + barGap);
const chartHeight = 250;

// Set canvas dimensions
canvas.width = chartWidth;
canvas.height = chartHeight;

// Function to draw a single bar
function drawBar(x, y, height, color) {
    ctx.fillStyle = color;
    ctx.fillRect(x, y, barWidth, height);
}

// Draw the bars
for (let i = 0; i < numBars; i++) {
    const barX = i * (barWidth + barGap);
    const barY = chartHeight - salesData[i].sales - 20;
    drawBar(barX, barY, salesData[i].sales, barColors[i]); // Adjust color as needed

    // Draw labels for each bar
    ctx.fillStyle = "black";
    ctx.font = "12px Arial";
    ctx.fillText(salesData[i].date, barX + barWidth / 2 - 5, chartHeight - 4);
    ctx.fillText(salesData[i].sales, barX + barWidth / 2 - 5, barY - 5);
}

// Add a heading to the chart
ctx.fillStyle = "black";
ctx.font = "18px Arial";
ctx.fillText("My Chart Title", (canvas.width/ 2) - 40, chartHeight - 230);

// Draw the x-axis
ctx.beginPath();
ctx.moveTo(0, chartHeight - 20);
ctx.lineTo(chartWidth, chartHeight - 20);
ctx.strokeStyle = "red";
ctx.stroke();

Setting Up the Canvas:

  • Accessing the Canvas: We first use JavaScript to find the HTML element with the ID "myChart" using document.getElementById("myChart"). This element represents the canvas where we'll draw the chart.
  • Getting the Drawing Context: Once we have the canvas element, we need a way to draw on it. We use the getContext("2d") method to obtain the 2D drawing context, which allows us to control what gets displayed on the canvas. We store this context in a variable called ctx.

Preparing the Data:

  • Sample Sales Data: We define an array called salesData to hold information about our chart. Each element in the array represents a month with its corresponding sales figures. We have data for "Jan" to "May" with separate values for projected and actual sales.
  • Color Palette: Another array named barColors stores the colors we'll use to represent different bars in the chart. We have red, orange, yellow, lime, and blue.

Chart Dimensions:

  • Bar Width and Gap: We define the width of each bar ( barWidth) and the space between bars ( barGap) in pixels.
  • Number of Bars: We calculate the total number of bars ( numBars) by getting the length of the salesData array.
  • Chart Size: Based on the individual bar width, gap, and total number of bars, we calculate the overall width ( chartWidth) of the chart. We also define a desired chartHeight.
  • Canvas Sizing: We set the actual width and height of the canvas element ( canvas) using the calculated chartWidth and chartHeight values. This ensures the chart fits within the designated space.

Drawing the Bars:

  1. drawBar Function: We define a reusable function called drawBar that takes four arguments:
    • x: The x-coordinate, defining the starting position of the bar on the horizontal axis.
    • y: The y-coordinate, defining the starting position of the bar on the vertical axis.
    • height: The height of the bar, which corresponds to the sales value for that month.
    • color: The color to be used for the specific bar.
  2. Drawing Individual Bars: We iterate through the salesData array using a loop. For each month:
    • We calculate the starting x and y coordinates for the bar using the current index, bar width, gap, and sales data.
    • We call the drawBar function with the calculated coordinates, sales data value (determining bar height), and corresponding color from the barColors array to draw the actual bar.
  3. Adding Labels: We iterate through the data again and use the ctx.fillText method to display the month name and sales value as text labels on top of each bar.

Finishing Touches:

  • Chart Title: We display a centered title "My Chart" above the bars using ctx.fillText.
  • X-axis: We draw a horizontal line at the bottom of the chart (y-axis) using ctx.beginPath, ctx.moveTo, ctx.lineTo, and ctx.stroke methods to represent the X-axis.

Now that you've built the code, it's time to see your creation come to life! Save the HTML, CSS, and JavaScript code into separate files (e.g., index.html, styles.css, script.js). Open the HTML file in your preferred web browser, and voila! You should see a basic bar chart displaying the sales data across months, with labels and an x-axis for reference. It should look like this:

bar chart

Conclusion

Congratulations! You've successfully created a basic bar chart using HTML, CSS, and JavaScript with the powerful canvas element.

Remember, this is just the beginning! Experiment with different data sets, customize colors, fonts, and add more elements like legends or tooltips to enhance your charts.

Explore further possibilities with canvas by delving into more complex chart types like line charts or pie charts.

By building upon this foundation and unleashing your creativity, you'll be well on your way to crafting informative and visually compelling charts that effectively communicate your message. Happy charting!