Introduction to
HTML5 Canvas

Wes Bos
wesbos.com
@wesbos

November 28, 2011

This presentation is 100% Flash Free.

What is canvas?

Part of the HTML5 Spec

A way to programatically draw pixels

Used for photo manipulation, drawing, animations/gaming, and even video processing

A single element within the dom.

Basically MS Paint for the web

HTML5 + JavaScript =

The HTML part of Canvas is as follows:

<canvas id="myCanvas" width="350" height="350">
  Your Browser doesn't support canvas
</canvas>

After that, we use JavaScript to draw to and manipulate the canvas.

Getting the canvas context

var myCanvas = document.getElementById('myCanvas'),
    ctx = myCanvas.getContext('2d');

console.log(myCanvas); // The canvas element in the dom
console.log(ctx); // the 2D Rendering context

Once we have the context we have access to all the methods that let us draw

Drawing Basics

Fills, strokes, rectangles & paths

Not Supported
function draw1() {
  var ex1 = document.getElementById('ex1'),
      ctx1 = ex1.getContext('2d');      
      // Drawing Rectangles 
      ctx1.fillStyle = "#BADA55";
      ctx1.strokeStyle = "goldenrod";
      ctx1.fillRect(10,20,100,100);
      ctx1.strokeRect(10,140,100,100);

      // Drawing Paths
      ctx1.fillStyle = "seaGreen";
      ctx1.beginPath();
      ctx1.moveTo(10, 300);
      ctx1.lineTo(200, 300); 
      ctx1.lineTo(10, 400); 
      ctx1.fill();
}     
        
Run Code

Arcs and Curves

function draw2() {
  var ex2 = document.getElementById('ex2'),
      ctx2 = ex2.getContext('2d');      
  // Drawing a circle
  ctx2.beginPath();
  ctx2.arc(75, 75, 50, 0, Math.PI*2, true); 
  ctx2.closePath();
  ctx2.fill();

  // Drawing Curves
  ctx2.moveTo(10, 230);
  ctx2.lineWidth = 5;
  ctx2.strokeStyle = "red"; // line color          
  ctx2.bezierCurveTo(140,10,388,10,250,500);
  ctx2.stroke();          
}          
        
Run Code

Gradients

function draw3() {
  var ex3 = document.getElementById('ex3'),
  ctx3 = ex3.getContext('2d');      
  // Basic Linear Gradient
  var grad = \
    ctx3.createLinearGradient(0,0,0,150);
  grad.addColorStop(0, 'red');
  grad.addColorStop(0.75, 'green');
  grad.addColorStop(1, 'blue');       
  ctx3.fillStyle = grad;
  ctx3.fillRect(0,0,300,200);
}          
        
Run Code

More of the drawing API

Transforms: Scale, Rotate, transform, translate

Draw images to canvas with drawImage()

Clip and Mask globalCompositeOperation

Manipulate Text with fillText(), strokeText(), measureText()

See the rest at http://simon.html5.org/dump/html5-canvas-cheat-sheet.html

Pixel level manipulation

One of the best parts of canvas is access to every pixel on the canvas

var pixels = ctx.getImageData(0,0,500,500);

Returns an object with CanvasPixelArray which is an array for every pixel.

Gives us the value for Red, Green, Blue and Alpha

We can then use a little math and manipulate those values and spit them back onto a canvas.

Instapuppy

Red Channel * 3, Green Channel * 2, Blue Channel - 40

Load puppy.jpg into Canvas 1 Manipulate puppy pixels and spit into canvas 2

Cool! More!

HTML5 Green Screen

Since we have access to pixel level details, we can find the pixels that are within a certain range of green and set the alpha to 0. This makes those pixels transparent!

Threshholds


Red is < 0

Green is > 0

Blue is < 0

Canvas Paint + NodeJS

Because canvas is just pixel data at its core, we can send that data to anyone in pretty much anyway we want.

Bind to click/drag → send data over nodeJS websocket → Get draw data → draw data to canvas

HTML5 Glasses!

Canvas plays nice with other HTML5 features, such as video.

1. We use navigator.getUserMedia() to access the webcam

2. We spit that video feed into an HTML5 video element

3. We dump the video pixels into a canvas element

4. Run the canvas frame through the CCV face detection library

5. Append hilarious glasses

Quite hardware intensive so we only get a framerate of about 1FPS. When using a pre-recorded video we get about 3-4FPS

getUserMedia() only currently available in a special build of Opera. CUTTING EDGE!

Ch-ch-ch-check
it out!

Done!

Questions?

@wesbos

Props to #DevTO