An impromptu
Barcamp presentation
that has something to
do with HTML5’s
<canvas> element
Ben Hodgson
@blahpro
Contains
JavaScript
Hello.
Disclaimer: I don’t really know what I’m talking about
<canvas>
• browser–based 2D drawing
• JavaScript API
<!DOCTYPE html>
<html>
<head>
<title>Canvas</title>
</head>
<body>
<canvas id="canvas_ftw"></canvas>
</body>
</html>
var canvas =
document.getElementById('canvas_ftw');
var ctx = canvas.getContext('2d');
ctx.fillStyle = "rgb(255,0,0)";
ctx.fillRect(30, 30, 50, 50);
ctx.clearRect(0, 0, width, height);
function Particle() {
this.radius = 2;
this.fill = "#000";
this.x = originX;
this.y = originY;
this.dx = 0; // px/sec
this.dy = 0; // px/sec
};
(function loop() {
simulate();
redraw();
setTimeout(loop, 0);
})();
function simulate() {
var now = new Date(),
interval = (now - lastSim) / 1000;
// loop over every particle in the scene
for(var i=0; i < scene.length; i++) {
scene[i].advanceSimulationBy(interval);
}
lastSim = now;
};
scene[i].advanceSimulationBy(interval);
• translates each particle according to its x/y velocity
• updates the x/y velocity to simulate gravity
• tests for collisions with the canvas edge
(bouncy bouncy)
Particle.prototype.draw = function(ctx) {
ctx.beginPath();
ctx.fillStyle = this.fill;
ctx.arc(this.x, this.y, this.radius, 0, TWO_PI, true);
ctx.closePath();
ctx.fill();
};
(function spawn() {
// Make a new particle
var p = new Particle();
p.fill = cycleColour();
p.radius = cycleSize();
p.dx = (Math.random() - 0.5) * initialVelocity;
p.dy = (Math.random() + 1.0) * initialVelocity / -2;
  
  // Add it to the scene
scene.push(p);
// Do it again in 100ms
setTimeout(spawn, 100);
// Limit the scene size
if(scene.length > maxParticles) {
scene.shift();
}
})();
Fork Me.
http://github.com/benhodgson/panvas

An Impromptu Introduction to HTML5 Canvas