Canvas

Graphics in JavaScript can be done with DOM Manipulation, SVG, or scripting the HTML <canvas> element. These notes cover the latter.

What is it?

The canvas element is an HTML element in which one draws, via scripts, 2-D graphics such as shapes and bitmaps. Drawing is done with a very low-level, procedural API.

Information and Tutorials:

Demos:

Getting Started

Let's look at some very trivial demos.

Shapes

Single click on this canvas to add 50 random rectangles and 50 random circles. Double click to clear the canvas.

Canvas isn't supported on this browser.

Fractal Mountains

Here is a random mountain range silohuette. Click on the canvas to generate a new silohuette. The ruggedness factor will be generated randomly.

Canvas isn't supported on this browser.

The Sierpinski Triangle

Here is the famous Sierpinski Triangle (Gasket) made from only 50,000 points.

Canvas isn't supported on this browser.

The API

The following is a summary from the canvas section of the HTML Living Standard.

class HTMLCanvasElement extends HTMLElement {
  width: unsigned long
  height: unsigned long
  toDataURL(type: DOMString?, ...args) -> DOMString
  getContext(contextId: DOMString, ...args) -> object
};

class CanvasRenderingContext2D {

  // Reference to the canvas
  canvas: readonly HTMLCanvasElement

  // State
  save()        // push state on state stack
  restore()     // pop state stack and restore state

  // Transformations (default transform is the identity matrix)
  scale(x, y: double)
  rotate(angle: double)
  translate(x, y: double)
  transform(a, b, c, d, e, f: double)
  setTransform(a, b, c, d, e, f: double)

  // Compositing
  globalAlpha: double = 1.0
  globalCompositeOperation: DOMString = "source-over"

  // Colors and styles
  strokeStyle: any = "black"
  fillStyle: any = "black"
  createLinearGradient(x0, y0, x1, y1: double) -> CanvasGradiant
  createRadialGradient(x0, y0, r0, x1, y1, r1: double) -> CanvasGradiant
  createPattern(image: HTMLImageElement, repetition: DOMString) -> CanvasPattern
  createPattern(image: HTMLCanvasElement, repetition: DOMString) -> CanvasPattern
  createPattern(image: HTMLVideoElement, repetition: DOMString) -> CanvasPattern

  // Line caps and joins
  lineWidth: double = 1
  lineCap: DOMString<"butt", "round", "square"> = "butt"
  lineJoin: DOMString<"round", "bevel", "miter"> = "miter"
  miterLimit: double = 10

  // Shadows
  shadowOffsetX: double = 0
  shadowOffsetY: double = 0
  shadowBlur: double = 0
  shadowColor: DOMString = "transparent black"

  // Rectangles
  clearRect(x, y, w, h: double)
  fillRect(x, y, w, h: double)
  strokeRect(x, y, w, h: double)

  // Path API
  beginPath()
  closePath()
  moveTo(x, y: double)
  lineTo(x, y: double)
  quadraticCurveTo(cpx, cpy, x, y: double)
  bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y: double)
  arcTo(x1, y1, x2, y2, radius: double)
  rect(x, y, w, h: double)
  arc(x, y, radius, startAngle, endAngle: double, anticlockwise: boolean = false)
  fill()
  stroke()
  clip()
  isPointInPath(x, y: double) -> double

  // Focus management
  drawFocusRing(element: Element, xCaret, yCaret: double, canDrawCustom: boolean = false) -> boolean

  // Text
  font: DOMString = "10px sans-serif"
  textAlign: DOMString<"start", "end", "left", "right", "center"> = "start"
  textBaseline: DOMString<"top", "hanging", "middle", "alphabetic", "ideographic", "bottom"> = "alphabetic"
  fillText(text: DOMString, x, y: double, maxWidth: double?)
  strokeText(text: DOMString, x, y: double, maxWidth: double?)
  measureText(text: DOMString) -> TextMetrics

  // Drawing images
  drawImage(image: HTMLImageElement, dx, dy, dw, dh)
  drawImage(image: HTMLImageElement, sx, sy, sw, sh, dx, dy, dw, dh)
  drawImage(image: HTMLCanvasElement, dx, dy, dw, dh)
  drawImage(image: HTMLCanvasElement, sx, sy, sw, sh, dx, dy, dw, dh)
  drawImage(image: HTMLVideoElement, dx, dy, dw, dh)
  drawImage(image: HTMLVideoElement, sx, sy, sw, sh, dx, dy, dw, dh)

  // Pixel manipulation
  createImageData(sw, sh: double) -> ImageData
  createImageData(data: ImageData) -> ImageData
  getImageData(sx, sy, sw, sh: double) -> ImageData
  putImageData(data: ImageData, dx, dy: double, dirtyX, dirtyY, dirtyW, dirtyH: double?)
};

class CanvasGradient {
  // opaque object
  addColorStop(offset: double, color: DOMString)
};

class CanvasPattern {
  // opaque object
};

class TextMetrics {
  width: readonly double
};

class ImageData {
  width: readonly unsigned long
  height: readonly unsigned long
  data: readonly CanvasPixelArray
};

class CanvasPixelArray {
  length: readonly unsigned long
  get (index: unsigned long) -> octet
  set (index: unsigned long, value: octet)
};

The Basics

Shapes

Bitmaps

Animation

This one is stolen from the Mozilla Developer Network

Canvas isn't supported on this browser.