HTML5 Canvas Cheat Sheet v1.x

Canvas element

Attributes

Name Type Default
width unsigned long 300
height unsigned long 150

Methods

Return Name
string toDataURL([Optional] string type, [Variadic] any args)
Object getContext(string contextId)

Html5 canvas element

<canvas id="myCanvas" width="500" height="300">

Html5 canvas element with fallback content

<canvas id="myCanvas" width="500" height="300">
your browser doesn't support canvas!
</canvas>

Get Data URL

var dataURL = canvas.toDataURL();

Render Canvas with Data URL

var imageObj = new Image();
imageObj.onload = function() {
context.drawImage(imageObj, 0, 0);
};

imageObj.src = dataURL;

2D Context

Attributes

Name Type Default
canvas HTMLCanvasObject [readonly]

Methods

Return Name
void save()
void restore()

2D Context

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

Webgl context (3d)

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

Push State onto Stack

context.save();

Pop State off of Stack

context.restore();

Transformation

Methods

Return Name
void scale(float x, float y)
void rotate(float angle)
void translate(float x, float y)
void transform(float m11, float m12, float m21, float m22, float dx, float dy)
void setTransform(float m11, float m12, float m21, float m22, float dx, float dy)

Translate

context.translate(x, y);

Scale

context.scale(x, y);

Rotate

context.rotate(radians);

Flip Horizontally

context.scale(-1, 1);

Flip Vertically

context.scale(1, -1);

Custom Transform

context.transform(a, b, c, d ,e, f);

Set Transform

context.setTransform(a, b, c, d ,e, f);

Shear

context.transform(1, sy, sx, 1, 0, 0);

Reset

context.setTransform(1, 0, 0, 1, 0, 0);

Image drawing

Methods

Return Name
void drawImage(Object image, float dx, float dy, [Optional] float dw, float dh)

Argument image can be of type HTMLImageElement, HTMLCanvasElement or HTMLVideoElement.

void drawImage(Object image, float sx, float sy, float sw, float sh, float dx, float dy, float dw, float dh)

Draw Image with default size

var imageObj = new Image();
imageObj.onload = function() {
context.drawImage(imageObj, x, y);
};
imageObj.src = 'path/to/my/image.jpg';

Draw image and set size

var imageObj = new Image();
imageObj.onload = function() {
context.drawImage(imageObj, x, y, width, height);
};
imageObj.src = 'path/to/my/image.jpg';

Crop image

var imageObj = new Image();
imageObj.onload = function() {
context.drawImage(imageObj, sx, sy, sw, sh, dx, dy, dw, dh);
};
imageObj.src = 'path/to/my/image.jpg';

Compositing

Attributes

Name Type Default
globalAlpha float 1.0
globalCompositeOperation string source-over

Supports any of the following values:

  • source-over
  • source-in
  • source-out
  • source-atop
  • destination-over
  • destination-in
  • destination-out
  • destination-atop
  • lighter
  • copy
  • xor

Alpha (Opacity)

context.globalAlpha = 0.5; // between 0 and 1

Composite Operations

context.globalCompositeOperation = 'source-atop|source-in|source-out|source-over|destination-atop|destination-in|destination-out|destination-over|lighter|xor|copy';

Line styles

Attributes

Name Type Default
lineWidth float 1.0
lineCap string butt

Supports any of the following values:

  • butt
  • round
  • square
lineJoin string miter

Supports any of the following values:

  • round
  • bevel
  • miter
miterLimit float 10

Line Cap

context.lineCap = 'butt|round|square';

Line Join

context.lineJoin = 'miter|round|bevel';

Colors, styles and shadows

Attributes

Name Type Default
strokeStyle any black
fillStyle any black
shadowOffsetX float 0.0
shadowOffsetY float 0.0
shadowBlur float 0.0
shadowColor string transparent black

Stroke

context.strokeStyle = 'red';
context.stroke();

Fill

context.fillStyle = 'red';
context.fillStyle = 'red';
context.fillStyle = '#ff0000';
context.fillStyle = '#f00';
context.fillStyle = 'rgb(255,0,0)';
context.fillStyle = 'rgba(255,0,0,1)';
context.fill();

Shadow

context.shadowColor = 'black';
context.shadowBlur = 20;
context.shadowOffsetX = 10;
context.shadowOffsetY = 10;

Methods

Return Name
CanvasGradient createLinearGradient(float x0, float y0, float x1, float y1)
CanvasGradient createRadialGradient(float x0, float y0, float r0, float x1, float y1, float r1)
CanvasPattern createPattern(Object image, string repetition)

image is HTMLImageElement or HTMLCanvasElement.

repetition supports any of the following values:

  • repeat (default)
  • repeat-x
  • repeat-y
  • no-repeat

Linear gradient

var grd = context.createLinearGradient(x1, y1, x2, y2);
grd.addColorStop(0, 'red');
grd.addColorStop(1, 'blue');
context.fillStyle = grd;
context.fill();

Radial gradient

var grd = context.createRadialGradient(x1, y1, radius1, x2, y2, radius2);
grd.addColorStop(0, 'red');
grd.addColorStop(1, 'blue');
context.fillStyle = grd;
context.fill();

Pattern

var imageObj = new Image();
imageObj.onload = function() {
var pattern = context.createPattern(imageObj, 'repeat');
context.fillStyle = pattern;
context.fill();
};
imageObj.src = 'path/to/my/image.jpg';

CanvasGradient interface

Return Name
void addColorStop(float offset, string color)

CanvasPattern interface

No attributes or methods.

Paths

Methods

Return Name
void beginPath()
void closePath()
void fill()
void stroke()
void clip()
void moveTo(float x, float y)
void lineTo(float x, float y)
void quadraticCurveTo(float cpx, float cpy, float x, float y)
void bezierCurveTo(float cp1x, float cp1y, float cp2x, float cp2y, float x, float y)
void arcTo(float x1, float y1, float x2, float y2, float radius)
void arc(float x, float y, float radius, float startAngle, float endAngle, boolean anticlockwise)
void rect(float x, float y, float w, float h)
boolean isPointInPath(float x, float y)

Begin Path

context.beginPath();

Line

context.lineTo(x, y);

Arc

context.arc(x, y, radius, startAngle, endAngle, counterClockwise);

Quadratic curve

context.quadraticCurveTo(cx, cy, x, y);

Bezier curve

context.bezierCurveTo(cx1, cy1, cx2, cy2, x, y);

Close Path

context.closePath();

Clip

// draw path here
context.clip();

Text

Attributes

Name Type Default
font string 10px sans-serif
textAlign string start

Supports any of the following values:

  • start
  • end
  • left
  • right
  • center
textBaseline string alphabetic

Supports any of the following values:

  • top
  • hanging
  • middle
  • alphabetic
  • ideographic
  • bottom

Methods

Return Name
void fillText(string text, float x, float y, [Optional] float maxWidth)
void strokeText(string text, float x, float y, [Optional] float maxWidth)
TextMetrics measureText(string text)

TextMetrics interface

Name Type Default
width float [readonly]

Fill Text

context.font = '40px Arial';
context.fillStyle = 'red';
context.fillText('Hello World!', x, y);

Stroke Text

context.font = '40pt Arial';
context.strokeStyle = 'red';
context.strokeText('Hello World!', x, y);

Bold Text

context.font = 'bold 40px Arial';

Italic Text

context.font = 'italic 40px Arial';

Text Align

context.textAlign = 'start|end|left|center|right';

Text Baseline

context.textBaseline = 'top|hanging|middle|alphabetic|ideographic|bottom';

Get Text Width

var width = context.measureText('Hello world').width;

Rectangles

Methods

Return Name
void clearRect(float x, float y, float w, float h)
void fillRect(float x, float y, float w, float h)
void strokeRect(float x, float y, float w, float h)

Draw rectangle

context.rect(x, y, width, height);
context.fill();
context.stroke();

Fill rectangle shorthand

context.fillRect(x, y, width, height);

Stroke rectangle shorthand

context.strokeRect(x, y, width, height);

Draw circle

context.arc(x, y, radius, 0, Math.PI * 2);
context.fill();
context.stroke();

Pixel manipulation

Methods

Return Name
ImageData createImageData(float sw, float sh)
ImageData getImageData(float sx, float sy, float sw, float sh)
void putImageData(ImageData imagedata, float dx, float dy, [Optional] float dirtyX, float dirtyY, float dirtyWidth, float dirtyHeight)

ImageData interface

Name Type Default
width unsigned long [readonly]
height unsigned long [readonly]
data CanvasPixelArray [readonly]

CanvasPixelArray interface

Name Type Default
length unsigned long [readonly]

Get Image Data

      var imageData = context.getImageData(x, y, width, height);
var data = imageData.data;

Loop Through Image Pixels

var imageData = context.getImageData(x, y, width, height);
var data = imageData.data;
var len = data.length;
var i, red, green, blue, alpha;

for(i = 0; i < len; i += 4) {
red = data[i];
green = data[i + 1];
blue = data[i + 2];
alpha = data[i + 3];
}

Loop Through Image Pixels With Coordinates

var imageData = context.getImageData(x, y, width, height);

var data = imageData.data;
var x, y, red, green, blue, alpha;

for(y = 0; y < imageHeight; y++) {
for(x = 0; x < imageWidth; x++) {
red = data[((imageWidth * y) + x) * 4];
green = data[((imageWidth * y) + x) * 4 + 1];
blue = data[((imageWidth * y) + x) * 4 + 2];
alpha = data[((imageWidth * y) + x) * 4 + 3];
}
}

Set Image Data

context.putImageData(imageData, x, y);