HTML canvas tutorial

Canvas consists of 2 parts

HTML

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

JS

var c = document.getElementById("cnv"); 
var ctx = c.getContext(“”); 

Required attributes

Id: It is not specific, but It is always a good idea to supply an id because this makes it much easier to identify it in a script.

Width: Initial width is 300px

Height: Initial height is 300px

Types of content

Fallback content

<canvas id=”cnvs” width=”600” 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 only 2 primitive shape - 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 different shapes, curved or not, of different width and of different color. A path, or even a subpath, can 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 shapes’ 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 takes the area of the source image specified by the rectangle whose top-left corner is (sx, sy) and whose width and height are sWidth and sHeight and draws it into the canvas, placing it on the canvas at (dx, dy) and scaling it to the size specified by dWidth and dHeight.

Transformations

Saves the entire state of the canvas. save()

Restores the most recently saved canvas state. restore()

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

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

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

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

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

Resets the current transform to the identity matrix. resetTransform()

Compositing & clipping

This sets the type of compositing operation to apply when drawing new shapes, where type is a string identifying which of the twelve compositing operations to use. globalCompositeOperation = type

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

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

Starts repeatedly executing the function specified by function every delay milliseconds. setInterval(function, delay)

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

Tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation before the next repaint. requestAnimationFrame(callback)

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 CanvasRenderingContext2D.addHitRegion()

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

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

Focus ring Experimental

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

Scrolls the current path or a given path into the view. CanvasRenderingContext2D.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