
333 - VISUALIZE TRAFFIC WITH DIY VECTOR GRAPHICS
HaCK
# 137
...
<h1>Soon, a line will appear!</h1>
<canvas id="picture" width="600" height="400"></canvas>
...
Then, in the <head> section of the HTML, include a link to a JavaScript le, which you will use to draw
the line (you’ll create this shortly). Also, insert an onload call to the function main() in the body tag,
as shown here (I’m also adding an inline style; please include your own external style sheet to dene
the page layout as you see t ):
...
<title>Drawing a line</title>
<script type="text/javascript" src="default.js"></script>
</head>
<body onload="main()" style="background-color: rgb(220,220,220)">
...
Next, create a default.js le 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 dened (picture),
then you’re conguring the line style, and then you’re moving the line from start point (x and y) to
end point. Now open your index.html le in a recent version of Opera, Firefox, or Safari, and ...