You Don’t Need Flash for Rich Graphs on a Web Page

Now, we have to calculate where we can start drawing on the canvas and how many pixels equal one coordinate in our user space data. The more elaborate legends we’ll want to use on the graph, the more these calculations will matter as we leave space for drawing text around the actual graph.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Rich Graph Example using HTML5's Canvas Element</title>
  </head>
  <body>
    <h1>Rich Graph Example using HTML5's Canvas Element</h1>
    <canvas id="graph1" width="500" height="200">
      This text is displayed if your browser sucks.
    </canvas>
  </body>
</html>

Now we get to the actual drawing of the graph. This is straight-forward 2D drawing that should be familiar to anyone who has done it with other technology.

    // Save the graphics context before we begin mucking with it.
    context.save();
 
    // Create a transform so that the graph portion of the chart can be
    // drawn using a bottom-left origin instead of the default upper-left.
    context.translate(0, yEnd);
    context.scale(1.0, -1.0);
 
    // Draw our path using the appropriate color.
    context.beginPath();
    context.strokeStyle = 'black';
    context.lineWidth = 5;
    context.moveTo(points[0].x, points[0].y);
    for (var i = 1; i < points.length; i++) {
      context.lineTo(points[i].x, points[i].y);
    }
    context.stroke();
    context.restore();

Published by

chadwick

Chad is a software developer from Colorado, USA. He's been working in the software industry since the 1980s and presently works for Alert Logic, a provider of managed security-as-a-service solutions for the Cloud. He spends way too much time bicycling or playing with cars.

2 thoughts on “You Don’t Need Flash for Rich Graphs on a Web Page”

  1. A lot of the places talking about the various HTML5 elements talk about the various state of the browsers. The canvas tag is supported well by Firefox, so that’s the important thing for now 🙂

    @MIke Lunt

Leave a Reply

Your email address will not be published. Required fields are marked *