More resources
- Mozilla's canvas tag tutorial.
- JavaScript: The Definitive Guide: the best tutorial/reference I know of.
- The official spec for the canvas element.
Why?
I've wanted to play with the canvas tag for a while now, and I finally have the perfect confluence of excuses to do so: I want to build an HTML-based rendering system for the output of my static analyzers; I'm introducing three engineering scholars to programming languages with graphics in JavaScript; and I'm building a super-optimizing compilation engine for dynamic languages like Scheme and JavaScript. Building a system for rendering univariate functions seems like a fun way to tip-toe into the canvas tag; below, you'll find an explanation of the system with a working demo.
Setting up the canvas
Setting up a canvas is straightforward; just drop in a canvas tag:
<canvas id="xy-graph" width="535" height="300"> CANVAS NOT SUPPORTED IN THIS BROWSER! </canvas>
The body of the canvas tag is what will be shown if the browser does not support the canvas tag.
Accessing the canvas
To draw on the canvas, grab ahold of the element itself:
var Canvas = document.getElementById('xy-graph');
And then grab its context:
if (Canvas.getContext) { Ctx = Canvas.getContext('2d'); // Rendering code goes here. } else { // Canvas not supported code goes here. }
To draw on the canvas, call methods on the Ctx
object.
Preparing the canvas
To prepare the canvas for drawing, it's best to clear what's already on the canvas with the clearRect(startX,startY,finishX,finishY)
method:
Ctx.clearRect(0,0,Canvas.width,Canvas.height) ;
Drawing lines
For graphing functions, we only need to draw lines, and we can do that with only four canvas context functions:
-
Ctx.beginPath()
starts recording a new sequence of line segments. -
Ctx.moveTo(x,y)
moves the pen to the coordinates(x,y)
. -
Ctx.lineTo(x,y)
drags the pen to the coordinates(x,y)
. -
Ctx.stroke()
connects all of the points in the path described.
Demo application: Graphing a function
Type JavaScript code in below that defines a function named F
, and the click
Draw! button further down.
The full, well-commented source code to this app is about 200 lines, and it's available down below.