HTML canvas tutorial

Canvas consists of 2 parts

HTML

<canvas id=”cnvs” width=”300” height=”300”></canvas>

JS

var c = document.getElementById(<cnv>); 
var ctx = c.getContext(""); 

Required attributes

ID: Although not required, supplying an ID is recommended as it eases the process of identifying it within a script

Width: Initial width is 300px

Height: Initial height is 300px

Types of content

Fallback content

<canvas id=”cnvs” width=”300” height=”300”>Your browser doesn’t support canvas!</canvas>

2D content

var ctx = canvas.getContext('2d');

3D content

var ctx = canvas.getContext('webgl');

Shapes

Canvas supports 2 primitive shapes: rectangles and paths

Rectangle

4 ways to create a rectangle

Adds a rectangular path to a currently open path rect(x, y, width, height)
A rectangular outline strokeRect(x, y, width, height)
Makes the rectangular area transparent clearRect(x, y, width, height)

Path

A path is a list of points connected by segments of lines that can be of varying shapes, curves, widths, and colors. Both paths and subpaths can also be closed.

To make shapes using paths:

Create the path beginPath()
Use path methods to draw into the path
Use stroke() or fill() the path to render it
Close the path closePath()

Where:

X

The x axis of the coordinate

Y

The y axis of the coordinate

Width

The rectangle’s width

Height

The rectangle’s height

Path methods:

For series of paths use Path2D Experimental object!

Or use SVG path data for both SVG and canvas.

Styles & Color

Colors

Sets the styles used when filling shapes fillStyle = color

Sets the styles for shape outline strokeStyle = color

Transparency

Applies the specified transparency value to all future shapes drawn on the canvas globalAlpha = transparencyValue

Patterns

Creates and returns a new canvas pattern object createPattern(image, type)

Canvas fill rules

Gradients

Linear gradient

Creates a linear gradient object createLinearGradient(x1, y1, x2, y2)

Round gradient

Creates a new color stop gradient.addColorStop(position, color)

Images

Control image scaling behavior

ctx.mozImageSmoothingEnabled = false;
ctx.webkitImageSmoothingEnabled = false;
ctx.msImageSmoothingEnabled = false;
ctx.imageSmoothingEnabled = false;

Get an image

from the same page:

the document.images collection

the document.getElementsByTagName() method

the ID of the image document.getElementById()

from other domain:

Does the hosting domain permits cross-domain access to the image?

YES: use crossorigin attribute of an <img>

NO: using the image can taint the canvas

create from scratch

Create new HTMLImageElement objects in our script

embedding an image via data: url

using frames from a <video></video>

Draw an image

drawImage(image, x, y)

Slice an image

drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)

Given an image, this function first takes the area of the source image specified by the rectangle with a top-left corner of (sx,sy) combined with a width and height of sWidth and sHeight to draw it into the canvas. Then, the function places it on a canvas at (dx,dy) and scales it to the size specified by dWidth and dHeight.

Transformations

save() Saves the entire state of the canvas

restore() Restores the most recently saved canvas state

translate(x, y) Moves the canvas and its origin on the grid

rotate(angle) Rotates the canvas clockwise around the current origin by the angle number of radians

scale(x, y) Scales the canvas units by x horizontally and by y vertically

transform(a, b, c, d, e, f) Multiplies the current transformation matrix with the matrix described by its arguments

setTransform(a, b, c, d, e, f) Resets the current transform to the identity matrix, and then invokes the transform() method with the same arguments

resetTransform() Resets the current transform to the identity matrix

Compositing & clipping

globalCompositeOperation = type Sets the type of compositing operation to apply when drawing new shapes. 'Type' is used to identify which of the twelve compositing operations to use.

clip() Turns the path currently being built into the current clipping path

Composite operation types

Animation

Basic animation steps

  1. Clear the canvas
  2. Save the canvas state
  3. Draw animated shapes
  4. Restore the canvas state

Schedule updates

setInterval(function, delay) Repeatedly executes the function specified in every delay milliseconds

setTimeout(function, delay) Executes the function specified by function in delay milliseconds

requestAnimationFrame(callback) Informs the browser to perform an animation and requests the browser call a specified function to update an animation before the next repaint

Pixel manipulation

Create Image data object

createImageData()

Get the pixel data from the content

getImageData()

Painting pixel data into content

putImageData()

Zooming and anti-aliasing

drawImage()

Saving images

Hit regions & accessibility

Hit regions Experimental

Adds a hit region to the canvas ctx.addHitRegion()

Removes the hit region with the specified id from the canvas ctx.removeHitRegion()

Removes all hit regions from the canvas ctx.clearHitRegions()

Focus ring Experimental

If a given element is focused, this method draws a focus ring around the current path ctx.drawFocusIfNeeded()

Scrolls the current path or given path into the view ctx.scrollPathIntoView()

Useful tips

Pre-render similar primitives or repeating objects on an off-screen canvas

Avoid floating-point coordinates and use integers instead

Don’t scale images in drawImage

Use multiple layered canvases for complex scenes

CSS for large background images

Scaling canvas using CSS transforms

Use the moz-opaque attribute (Gecko only)

Batch canvas calls together

Avoid unnecessary canvas state changes

Render screen differences only, not the whole new state

Avoid the shadowBlur property whenever possible

Avoid text rendering whenever possible

Try different ways to clear the canvas (clearRect() vs. fillRect() vs. resizing the canvas)

With animations, use: window.requestAnimationFrame() instead of window.setInterval()

Be careful with heavy physics libraries

Canvas inspiration