• Like

Loading…

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

An Impromptu Introduction to HTML5 Canvas

  • 875 views
Uploaded on

 

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
875
On Slideshare
0
From Embeds
0
Number of Embeds
2

Actions

Shares
Downloads
13
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. An impromptuBarcamp presentationthat has something to do with HTML5’s <canvas> element Ben Hodgson @blahpro
  • 2. ContainsJavaScript
  • 3. Hello.
  • 4. Disclaimer: I don’t really know what I’m talking about
  • 5. <canvas>• browser–based 2D drawing• JavaScript API
  • 6. <!DOCTYPE html><html><head> <title>Canvas</title></head><body> <canvas id="canvas_ftw"></canvas></body></html>
  • 7. var canvas = document.getElementById(canvas_ftw);var ctx = canvas.getContext(2d);ctx.fillStyle = "rgb(255,0,0)";ctx.fillRect(30, 30, 50, 50);
  • 8. ctx.clearRect(0, 0, width, height);
  • 9. function Particle() { this.radius = 2; this.fill = "#000"; this.x = originX; this.y = originY; this.dx = 0; // px/sec this.dy = 0; // px/sec};
  • 10. (function loop() { simulate(); redraw(); setTimeout(loop, 0);})();
  • 11. 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; };
  • 12. 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)
  • 13. 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();};
  • 14. (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(); }})();
  • 15. Fork Me.http://github.com/benhodgson/panvas