An Impromptu Introduction to HTML5 Canvas

1,150 views

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,150
On SlideShare
0
From Embeds
0
Number of Embeds
48
Actions
Shares
0
Downloads
14
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

An Impromptu Introduction to HTML5 Canvas

  1. 1. An impromptu Barcamp presentation that has something to do with HTML5’s <canvas> element Ben Hodgson @blahpro
  2. 2. Contains JavaScript
  3. 3. Hello.
  4. 4. Disclaimer: I don’t really know what I’m talking about
  5. 5. <canvas> • browser–based 2D drawing • JavaScript API
  6. 6. <!DOCTYPE html> <html> <head> <title>Canvas</title> </head> <body> <canvas id="canvas_ftw"></canvas> </body> </html>
  7. 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. 8. ctx.clearRect(0, 0, width, height);
  9. 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. 10. (function loop() { simulate(); redraw(); setTimeout(loop, 0); })();
  11. 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. 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. 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. 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. 15. Fork Me. http://github.com/benhodgson/panvas

×