Visualize Traffic with DIY Vector

you will learn how to create your own traffic chart using the incredibly cool Canvas framework, which can produce vector graphics and animations with a little bit of HTML and JavaScript. All code referenced in this hack is also available in a single zip file at http://blogoscoped.com/googleappshacks/canvas.zip. Although setting up Canvas may take a little longer than using, say, the Google Charts API  it's also much more flexible, and can even include animated charts.

Draw Something Using Canvas

Canvas is a vector graphics framework which works in most popular browsers today including Firefox, Opera and Safari, and does not require a plug-in like Flash does. Internet Explorer too can render Canvas code, at least with a little tweak you'll see further below. Canvas can be used to have a web page show 2D and 3D drawings, games, charts, applications, animations, and much more.

A longer canvas tutorial is available at http://developer.mozilla.org/en/docs/Canvas_tutorial (explaining how to draw rectangles, curves, imported images, and much more), but let's just see what you need to draw a simple line. First, create a file named index.html and open it with a plain text editor. Create a basic page like the following;

 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; CHARSET=UTF-8" />
  <title>Drawing a line</title>
</head>
<body>
  <h1>Soon, a line will appear!</h1>
</body>
</html>

       

So far, that's all plain XHTML. Now somewhere in the <body> of the page, put the canvas tag:

Next, create a default.js file containing the following JavaScript, and put it in the same folder as index.html:
function main() {
    // grab the canvas
    var canvas = document.getElementById('picture');
    var ctx = canvas.getContext('2d');

    // set the color and line width
    ctx.strokeStyle = 'rgba(40,200,180,1)';
    ctx.lineWidth = 8;

    // draw a line
    ctx.beginPath();
    ctx.moveTo(40, 140);
    ctx.lineTo(240, 40);
    ctx.stroke();
}

That's not a lot of code—you're grabbing the canvas element using the ID you defined