HTML5 Canvas

Demos for Beginners, by Hannah

back to projects

I read Mark Pilgrim's book HTML5: Up and Running, and thought I'd do an example with the new canvas element.

"A canvas is a rectangle on your page in which you can use JavaScript to draw anything you want." - Mark Pilgrim

Wise words indeed.

Let's try a simple example:

<canvas id="sinecanvas" width="700" height="100" style="border:2px solid;"></canvas>


var sineCanvas = document.getElementById("sinecanvas");
var sineContext = sineCanvas.getContext("2d");

//  As Pilgrim explains, you can trace your figure as you might in pencil before
//  the more indellible stroke.
sineContext.moveTo(0, 50);
for(var x = 0 ; x < 700 ; x++) {
	sineContext.lineTo(x, Math.sin(x/5) * 40 + 50);
// and the stroke.
sineContext.strokeStyle = "#F0F";
sineContext.lineWidth = 2;


And that's about all there is to it.

Now, let's try something a bit more complex. Of course, if you can draw one picture, you can draw several -- thus, animation. A little basic kinematics and some handling of mouse events give you this. (Those of you also beginners in physics will be able to spot the problem with my calculation.)

Bouncing Balls, or Thermal Energy

Number of Balls:

Click to hold ball stationary. Click and drag to accelerate ball.

View Source Code