The <canvas> element

Bill Mill

billmill.org

Soteria Network Technologies

What is <canvas>?

Why <canvas>?

iPhone

  • The iPhone doesn't have flash; instead it has canvas

Why Not <canvas>?

<canvas> summary

Breakout in 30 Minutes

  • To get a feel for working with <canvas>, let's build something with it: a game!
  • We'll do a simple clone of the 80s game Breakout

Let's get started!

<canvas id="canvas" 
    width="300" height="300" 
    style="border:1px solid;">
</canvas>


ctx = $("#canvas")
      .getContext("2d");
ctx.arc(75,75,10,0,Math.PI*2,true); 
ctx.fill();

Don't be a Square

ctx.fillStyle = 'rgb(200,10,10)';
ctx.fillRect(150, 290, 75, 10);

Movin'

function startdraw() {
  init();
  intervalID = 
    setInterval(draw, 20);
}

function draw() {
  ctx.clearRect(0,0,300,300);

  //draw the ball 
  //exactly as before

  x += dx;
  y += dy;
}
  • setInterval function sets draw() to run every 20 milliseconds
  • clear the screen every time
  • to move the ball, simply add our dx and dy values
  • get somebody to provide dx and dy

Bounce!

var WIDTH = 300;
var HEIGHT = 300;

function draw() {
  //clear screen and draw ball

  x += dx;
  y += dy;

  if (x > WIDTH || x < 0)
    dx = -dx;

  if (y > HEIGHT || y < 0)
    dy = -dy;
}

The Keyboard Part 1

function doKeyDown(evt) {
  if (evt.keyCode == 39)
    rightDown = true;
  else if (evt.keyCode == 37)
    leftDown = true;
}

function doKeyUp(evt) {
  if (evt.keyCode == 39)
    rightDown = false;
  else if (evt.keyCode == 37)
    leftDown = false;
}

$(document).keydown(doKeyDown);
$(document).keyup(doKeyUp);

The Keyboard Part 2

function draw() {
  //draw the paddle and ball

  if (leftDown)
    paddlex -= paddledx;
  else if (rightDown)
    paddlex += paddledx;
}

I Hates Meeses to Pieces

function mouseMove(evt) {

  if (evt.pageX > canvasMinX 
  &&  evt.pageX < canvasMaxX)

    paddlex = 
      evt.pageX - canvasMinX;
}

$(document).mousemove(mouseMove);

Add Some Bricks

for (i=0; i < NROWS; i++) {
  for (j=0; j < NCOLS; j++) {

    if (bricks[i][j] == 1) {

      ctx.fillRect(
        j * BRICKWIDTH,
        i * BRICKHEIGHT,
        BRICKWIDTH,
        BRICKHEIGHT);
    }
  }
}

And some color...

Some cool demos