How to Create a Bar Graph in JavaScript?

Estimated read time 2 min read

To create a bar graph in JavaScript, you can use the HTML5 canvas element and JavaScript to draw the bars and axes. Here’s a basic example of how to create a bar graph in JavaScript:

<canvas id="myCanvas" width="500" height="500"></canvas>
<script>
  let canvas = document.getElementById("myCanvas");
  let ctx = canvas.getContext("2d");

  let data = [50, 60, 70, 80, 90, 100];
  let barWidth = 50;
  let barSpacing = 10;
  let x = 0;

  for (let i = 0; i < data.length; i++) {
    ctx.fillRect(x, canvas.height - data[i], barWidth, data[i]);
    x += barWidth + barSpacing;
  }
</script>

In this example, the canvas element is defined with an id of “myCanvas” and a width and height of 500 pixels. The JavaScript code then retrieves a reference to the canvas element and creates a 2D rendering context, which is stored in the ctx variable.

The data array stores the data that will be used to generate the bars in the graph. The barWidth variable specifies the width of each bar, and the barSpacing variable specifies the spacing between each bar. The x variable keeps track of the current x-coordinate, which will be used to position each bar.

The for loop iterates over the data array, and on each iteration, the fillRect method is called on the rendering context to draw a filled rectangle representing a bar in the graph. The x variable is updated on each iteration to position the next bar.

This is just a basic example, and there are many ways to enhance and customize the appearance of the bar graph, such as adding labels, colors, and gridlines.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply