Canvasimo(Version: 0.6.8)

An HTML5 canvas drawing library, with 150+ useful methods, jQuery-like fluent interface, and cross-browser compatibility enhancements to make your life easier. Includes methods for drawing shapes not supported by the standard canvas API, loops, intuitive font control, and a host of helper methods for creating colors, calculating distances, converting angles, and much more.

Circle CI Status BadgeNPMGitHubIssues

Demo

Looks like this browser doesn't support the canvas element, or you have javascript disabled.

Features

  • Fluent interface
  • Idiomatic method names
  • Alias original canvas methods
  • Improved browser compatibility
  • Additional drawing methods
  • Useful helper functions

About

Canvasimo (canvas in my opinion) started off as a simple concept - create wrappers for the standard canvas API to create a fluent interface, and allow access to canvas attributes with getters and setters.

This quickly evolved into a project that not only wrapped the existing canvas API, but added some additional methods (e.g. for creating rounded rectangles), and ensured that experimental features (such as reset transform and ellipse) worked in all browsers.

Along the way, I realised that a lot of the canvas attributes & methods were not very idiomatic, and so I came up with some more suitable method / attribute names.

For example, shape drawing is broken into 3 types: plotShape, fillShape, and strokeShape. You'll find these 3 methods for almost every shape, e.g. plotRect, fillRect and strokeRect. All the original methods are still available as aliases, e.g. rect.

Similarly attributes regarding lines and strokes had a mixed set of names, so to simplify this, any style related attributes are referred to as stroke, and line is now a shape. For example, where you previously had strokeStyle and lineWidth, you now have stroke and strokeWidth, both of which are available through getters and setters; setStroke, setStrokeWidth. You can, however, still use their aliases; setStrokeStyle, setLineWidth.

Additionally, any methods that previously relied on setting the stroke or fill color before-hand, can now optionally have a color passed as their final argument, e.g. fillRect(0, 0, 10, 10, 'black'), strokeLine(0, 0, 0, 20, 'red'). And similarly, the fill and stroke methods can now be passed a color; fill('red'), stroke('green'), fillCanvas('blue').

Examples

Basic shapes

Looks like this browser doesn't support the canvas element, or you have javascript disabled.
import Canvasimo from 'canvasimo';

const element = document.getElementById('example-basic-shapes');

if (!element) {
  throw new Error('Could not find canvas element for basic shapes example');
}

const canvas = new Canvasimo(element as HTMLCanvasElement);
const rect = canvas.getBoundingClientRect();

const randoms = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map(() => Math.random());

canvas
  .setDensity(2)
  .setSize(rect.width, rect.height);

const draw = () => {
  const { width } = canvas.getBoundingClientRect();
  const height = canvas.getHeight();

  canvas
    .clearCanvas()
    .setSize(width, height)
    .fillCanvas('#EEEEEE')
    .save()
    .translate(width / 2, height / 2)
    .rotate(canvas.getRadiansFromDegrees(-90))
    .setOpacity(0.25)
    .fillStar(0, 0, 50, 5, false, 'red')
    .restore()
    .strokeCircle(width * 0.25, height / 2, 30, false, 'black')
    .strokeBurst(width * 0.25, height / 2, 40, 50, 8, false, 'black')
    .strokeRoundedRect(width * 0.75 - 20, height / 2 - 20, 40, 40, 10, 'black')
    .repeat(10, (index) => {
      const y = canvas.map(index, 0, 10, 0, height) + height / 10 / 2;

      canvas
        .beginPath()
        .strokeLine(10, y, width - 10, y, 'green');
    })
    .tap(() => {
      const path = randoms.map((value, index) => ({
        x: canvas.getFractionOfWidth(1 / (randoms.length - 1)) * index,
        y: canvas.map(value, 0, 1, 0, height),
      }));

      canvas
        .beginPath()
        .setStrokeWidth(2)
        .strokePath(path, 'blue');
    });
};

draw();

window.addEventListener('resize', draw);

Multiline text

Looks like this browser doesn't support the canvas element, or you have javascript disabled.
import Canvasimo from 'canvasimo';

const element = document.getElementById('example-multiline-text');

if (!element) {
  throw new Error('Could not find canvas element for multiline text example');
}

const MARGIN = 10;
const FONT_SIZE = 14;
const canvas = new Canvasimo(element as HTMLCanvasElement);
const rect = canvas.getBoundingClientRect();

canvas
  .setDensity(2)
  .setSize(rect.width, rect.height);

const draw = () => {
  const { width } = canvas.getBoundingClientRect();
  const height = canvas.getHeight();

  const multilineTextArea = Math.min(width / 3 * 2, 400);
  const multilineTextOffset = (width - multilineTextArea) / 2;
  const multilineTextWidth = (multilineTextArea - MARGIN * 6) / 3;

  canvas
    .clearCanvas()
    .setSize(width, height)
    .fillCanvas('#FFFFFF')
    .setTextBaseline('top')
    .setFontFamily('arial')
    .setFontSize(FONT_SIZE)
    .fillText(
      'Regular text that does not have newlines or automatic wrapping',
      MARGIN,
      MARGIN,
      null,
      'black'
    )
    .fillTextMultiline(
      'Text with newline after this...\n...so this is on a newline',
      MARGIN,
      FONT_SIZE * 2
    )
    .setTextAlign('center')
    .setFontSize(FONT_SIZE - 2)
    .fillTextMultiline(
      'Try resizing the window! :D',
      width / 2,
      FONT_SIZE * 4,
      width - MARGIN * 2,
      undefined,
      undefined,
      '#555555'
    )
    .setFontSize(FONT_SIZE)
    .setFill('black')
    .translate(multilineTextOffset, 0)
    .strokeLine(0, 0, 0, height, '#AAAAAA')
    .setTextAlign('left')
    .fillTextMultiline(
      'normal\nText that automatically wraps but never breaks words',
      MARGIN,
      MARGIN + FONT_SIZE * 5,
      multilineTextWidth,
      'normal'
    )
    .translate(MARGIN * 2 + multilineTextWidth, 0)
    .strokeLine(0, 0, 0, height, '#AAAAAA')
    .setTextAlign('center')
    .fillTextMultiline(
      'break-word\nText that automatically wraps and breaks words if necessary',
      MARGIN + multilineTextWidth / 2,
      MARGIN + FONT_SIZE * 5,
      multilineTextWidth,
      'break-word'
    )
    .translate(MARGIN * 2 + multilineTextWidth, 0)
    .strokeLine(0, 0, 0, height, '#AAAAAA')
    .setTextAlign('right')
    .fillTextMultiline(
      'break-all\nText that automatically wraps and always breaks words',
      MARGIN + multilineTextWidth,
      MARGIN + FONT_SIZE * 5,
      multilineTextWidth,
      'break-all'
    )
    .translate(MARGIN * 2 + multilineTextWidth, 0)
    .strokeLine(0, 0, 0, height, '#AAAAAA');
};

draw();

window.addEventListener('resize', draw);

Documentation

Canvas element

A collection of methods for getting and setting various properties of the canvas element.

getCanvasAlias: getElement

Get the canvas element.

canvas.getCanvas() => HTMLCanvasElement;

setDensity

Set the canvas pixel density.

canvas.setDensity(density: number) => Canvasimo;

getDensity

Get the canvas pixel density.

canvas.getDensity() => number;

setSize

Set the canvas dimensions.

canvas.setSize(size: Size) => Canvasimo;
canvas.setSize(width: number, height: number) => Canvasimo;
type Size = { width: number; height: number; };

getSize

Get the canvas dimensions.

canvas.getSize() => Size;
type Size = { width: number; height: number; };

setWidth

Set the canvas width.

canvas.setWidth(width: number) => Canvasimo;

getWidth

Get the canvas width.

canvas.getWidth() => number;

setHeight

Set the canvas height.

canvas.setHeight(height: number) => Canvasimo;

getHeight

Get the canvas height.

canvas.getHeight() => number;

getBoundingClientRect

Get the canvas size & position on screen.

canvas.getBoundingClientRect() => ClientRect;

Context

'A collection of methods for retrieving a canvas context or information about the context.

getContext

Get the standard canvas context (used for drawing).

canvas.getContext(type: string, contextAttributes?: CanvasContextAttributes) => CanvasContext;
type CanvasContextAttributes = Canvas2DContextAttributes | WebGLContextAttributes;
type CanvasContext = CanvasRenderingContext2D | WebGLRenderingContext | null;

getCurrentContext

Get canvas context used by Canvasimo (2d).

canvas.getCurrentContext() => CanvasRenderingContext2D;

getCurrentContextType

Get the context type used by Canvasimo ('2d', 'webgl', etc).

canvas.getCurrentContextType() => "2d";

getContextAttributes

Get the context attributes used.

canvas.getContextAttributes() => CanvasContextAttributes;
type CanvasContextAttributes = Canvas2DContextAttributes | WebGLContextAttributes;

Solid Shapes

A collection of methods for plotting or drawing solid shapes - those that create a new shape when invoked, and are self closing.

plotRectAlias: rect

Plot a rectangle that can then have a fill or stroke applied to it.

canvas.plotRect(x: number, y: number, width: number, height: number) => Canvasimo;

strokeRect

Plot a rectangle and apply a stroke to it.

canvas.strokeRect(x: number, y: number, width: number, height: number, color?: string) => Canvasimo;

fillRect

Plot a rectangle and apply a fill to it.

canvas.fillRect(x: number, y: number, width: number, height: number, color?: string) => Canvasimo;

plotRoundedRect

Plot a rounded rectangle that can then have a fill or stroke applied to it.

canvas.plotRoundedRect(x: number, y: number, width: number, height: number, radius: number) => Canvasimo;

strokeRoundedRect

Plot a rounded rectangle and apply a stroke to it.

canvas.strokeRoundedRect(x: number, y: number, width: number, height: number, radius: number, color?: string) => Canvasimo;

fillRoundedRect

Plot a rounded rectangle and apply a fill to it.

canvas.fillRoundedRect(x: number, y: number, width: number, height: number, radius: number, color?: string) => Canvasimo;

plotCircle

Plot a circle that can then have a stroke or fill applied to it.

canvas.plotCircle(x: number, y: number, radius: number, anticlockwise?: boolean) => Canvasimo;

strokeCircle

Plot a circle and apply a stroke to it.

canvas.strokeCircle(x: number, y: number, radius: number, anticlockwise?: boolean, color?: string) => Canvasimo;

fillCircle

Plot a circle and apply a fill to it.

canvas.fillCircle(x: number, y: number, radius: number, anticlockwise?: boolean, color?: string) => Canvasimo;

plotPoly

Plot a polygon that can then have a stroke or fill applied to it.

canvas.plotPoly(x: number, y: number, radius: number, sides: number, anticlockwise?: boolean) => Canvasimo;

strokePoly

Plot a polygon and apply a stoke to it.

canvas.strokePoly(x: number, y: number, radius: number, sides: number, anticlockwise?: boolean, color?: string) => Canvasimo;

fillPoly

Plot a polygon and apply a fill to it.

canvas.fillPoly(x: number, y: number, radius: number, sides: number, anticlockwise?: boolean, color?: string) => Canvasimo;

plotStar

Plot a star that can then have a stroke or fill applied to it.

canvas.plotStar(x: number, y: number, radius1: number, sides: number, anticlockwise?: boolean) => Canvasimo;

strokeStar

Plot a star and apply a stoke to it.

canvas.strokeStar(x: number, y: number, radius1: number, sides: number, anticlockwise?: boolean, color?: string) => Canvasimo;

fillStar

Plot a star and apply a fill to it.

canvas.fillStar(x: number, y: number, radius1: number, sides: number, anticlockwise?: boolean, color?: string) => Canvasimo;

plotBurst

Plot a burst that can then have a stroke or fill applied to it.

canvas.plotBurst(x: number, y: number, radius1: number, radius2: number, sides: number, anticlockwise?: boolean) => Canvasimo;

strokeBurst

Plot a burst and apply a stoke to it.

canvas.strokeBurst(x: number, y: number, radius1: number, radius2: number, sides: number, anticlockwise?: boolean, color?: string) => Canvasimo;

fillBurst

Plot a burst and apply a fill to it.

canvas.fillBurst(x: number, y: number, radius1: number, radius2: number, sides: number, anticlockwise?: boolean, color?: string) => Canvasimo;

plotPixel

Plot a single pixel that can then have a stroke or fill applied to it.

canvas.plotPixel(x: number, y: number) => Canvasimo;

strokePixel

Plot a single pixel and apply a stroke to it.

canvas.strokePixel(x: number, y: number, color?: string) => Canvasimo;

fillPixel

Plot a single pixel and apply a fill to it.

canvas.fillPixel(x: number, y: number, color?: string) => Canvasimo;

plotClosedPath

Plot a closed path that can then have a stroke or fill applied to it.

canvas.plotClosedPath(points: Points) => Canvasimo;
type Points = Array<{x: number, y: number}> | Array<[number, number]> | number[];

strokeClosedPath

Plot a closed path and apply a stroke to it.

canvas.strokeClosedPath(points: Points, color?: string) => Canvasimo;
type Points = Array<{x: number, y: number}> | Array<[number, number]> | number[];

fillClosedPath

Plot a closed path and apply a fill to it.

canvas.fillClosedPath(points: Points, color?: string) => Canvasimo;
type Points = Array<{x: number, y: number}> | Array<[number, number]> | number[];

Open Shapes

A collection of methods for plotting or drawing open shapes - those that create a new shape when invoked, but are not self closing.

plotLine

Plot a line that can then have a stroke or fill applied to it.

canvas.plotLine(x1: number, y1: number, x2: number, y2: number) => Canvasimo;

strokeLine

Plot a line and apply a stroke to it.

canvas.strokeLine(x1: number, y1: number, x2: number, y2: number, color?: string) => Canvasimo;

plotLength

Plot a line, by length & angle, that can then have a stroke or fill applied to it.

canvas.plotLength(x1: number, y1: number, length: number, angle: number) => Canvasimo;

strokeLength

Plot a line, by length & angle, and apply a stroke to it.

canvas.strokeLength(x1: number, y1: number, length: number, angle: number, color?: string) => Canvasimo;

plotPath

Plot a path, that is not self closing, that can have a stroke or fill applied to it.

canvas.plotPath(points: Points) => Canvasimo;
type Points = Array<{x: number, y: number}> | Array<[number, number]> | number[];

strokePath

Plot a path, that is not self closing, and apply a stroke to it.

canvas.strokePath(points: Points, color?: string) => Canvasimo;
type Points = Array<{x: number, y: number}> | Array<[number, number]> | number[];

fillPath

Plot a path, that is not self closing, and apply a fill to it.

canvas.fillPath(points: Points, color?: string) => Canvasimo;
type Points = Array<{x: number, y: number}> | Array<[number, number]> | number[];

Paths

A collection of methods for plotting or drawing paths - shapes that can be connected to create more complex shapes.

plotArcAlias: arc

Plot an arc that can have a stroke or fill applied to it.

canvas.plotArc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean) => Canvasimo;

strokeArc

Plot an arc and apply a stroke to it.

canvas.strokeArc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean, color?: string) => Canvasimo;

fillArc

Plot an arc and apply a fill to it.

canvas.fillArc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean, color?: string) => Canvasimo;

plotEllipseAlias: ellipse

Plot an ellipse that can then have a stroke or fill applied to it.

canvas.plotEllipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, anticlockwise?: boolean) => Canvasimo;

strokeEllipse

Plot an ellipse and apply a stroke to it.

canvas.strokeEllipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, anticlockwise?: boolean, color?: string) => Canvasimo;

fillEllipse

Plot an ellipse and apply a fill to it.

canvas.fillEllipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, anticlockwise?: boolean, color?: string) => Canvasimo;

Text

A collection of methods for drawing text, and getting and setting properties related to text rendering.

strokeText

Draw a text with a stroke.

canvas.strokeText(text: string, x: number, y: number, maxWidth?: number, color?: string) => Canvasimo;

fillText

Draw a text with a fill.

canvas.fillText(text: string, x: number, y: number, maxWidth?: number, color?: string) => Canvasimo;

strokeTextMultiline

Draw text with a stroke, wrapped at newlines and automatically wrapped if the text exceeds the maxWidth. If no maxWidth is specified text will only wrap at newlines (wordBreak is ignore). Words will not break by default (normal) and therefore may overflow. break-all will break words wherever possible, and break-word will only break words if there is not enough room. The lineHeight parameter is a multiplier for the font size, and defaults to 1.

canvas.strokeTextMultiline(text: string, x: number, y: number, maxWidth?: number, wordBreak?: WordBreak, lineHeight?: number, color?: string) => Canvasimo;
type WordBreak = 'normal' | 'break-word' | 'break-all';

fillTextMultiline

Draw text with a fill, wrapped at newlines and automatically wrapped if the text exceeds the maxWidth. If no maxWidth is specified text will only wrap at newlines (wordBreak is ignore). Words will not break by default (normal) and therefore may overflow. break-all will break words wherever possible, and break-word will only break words if there is not enough room. The lineHeight parameter is a multiplier for the font size, and defaults to 1.

canvas.fillTextMultiline(text: string, x: number, y: number, maxWidth?: number, wordBreak?: WordBreak, lineHeight?: number, color?: string) => Canvasimo;
type WordBreak = 'normal' | 'break-word' | 'break-all';

getTextSizeAlias: measureText

Get information about the size text will be drawn.

canvas.getTextSize(text: string) => TextMetrics;

setTextAlign

Set the horizontal text alignment.

canvas.setTextAlign(value: TextAlign) => Canvasimo;
type TextAlign = 'left' | 'right' | 'center' | 'start' | 'end';

getTextAlign

Get the horizontal text alignment.

canvas.getTextAlign() => TextAlign;
type TextAlign = 'left' | 'right' | 'center' | 'start' | 'end';

setTextBaseline

Set the vertical text alignment.

canvas.setTextBaseline(value: TextBaseline) => Canvasimo;
type TextBaseline = 'top' | 'hanging' | 'middle' | 'alphabetic' | 'ideographic' | 'bottom';

getTextBaseline

Get the vertical text alignment.

canvas.getTextBaseline() => TextBaseline;
type TextBaseline = 'top' | 'hanging' | 'middle' | 'alphabetic' | 'ideographic' | 'bottom';

Fonts

A collection of methods for getting and setting font styles and variations.

setFont

Set the font to use.

canvas.setFont(font: string) => Canvasimo;

getFont

Get the font that is being used. This returns the exact CanvasRenderingContext2D.font string.

canvas.getFont() => string;

setFontFamily

Set the font family to use.

canvas.setFontFamily(family: string) => Canvasimo;

getFontFamily

Get the font that is being used.

canvas.getFontFamily() => string;

setFontSize

Set the font size to use.

canvas.setFontSize(size: string | number) => Canvasimo;

getFontSize

Get the font size that is being used. Returns null if using a special font e.g. caption, icon, menu.

canvas.getFontSize() => number;

setFontStyle

Set the font style to use.

canvas.setFontStyle(style: string) => Canvasimo;

getFontStyle

Get the font style that is being used. Returns null if using a special font e.g. caption, icon, menu.

canvas.getFontStyle() => string;

setFontVariant

Set the font variant to use.

canvas.setFontVariant(variant: string) => Canvasimo;

getFontVariant

Get the font variant that is being used. Returns null if using a special font e.g. caption, icon, menu.

canvas.getFontVariant() => string;

setFontWeight

Set the font weight to use.

canvas.setFontWeight(weight: string | number) => Canvasimo;

getFontWeight

Get the font weight that is being used. Returns null if using a special font e.g. caption, icon, menu.

canvas.getFontWeight() => string | number;

Stroke Styles

A collection of methods for getting and setting stroke styles, and applying strokes to existing shapes.

stroke

Apply a stroke to the current shape.

canvas.stroke(color?: string) => Canvasimo;
canvas.stroke(path?: Path2D) => Canvasimo;
canvas.stroke(color: string, path: Path2D) => Canvasimo;

setStrokeAlias: setStrokeStyle

Set the stroke style to use.

canvas.setStroke(value: FillOrStrokeStyle) => Canvasimo;
type FillOrStrokeStyle = string | CanvasGradient | CanvasPattern;

getStrokeAlias: getStrokeStyle

Get the stroke style that is being used.

canvas.getStroke() => FillOrStrokeStyle;
type FillOrStrokeStyle = string | CanvasGradient | CanvasPattern;

setStrokeCapAlias: setLineCap

Set the stroke cap to use.

canvas.setStrokeCap(value: LineCap) => Canvasimo;
type LineCap = 'butt' | 'round' | 'square';

getStrokeCapAlias: getLineCap

Get the stroke cap that is being used.

canvas.getStrokeCap() => LineCap;
type LineCap = 'butt' | 'round' | 'square';

setStrokeDashAlias: setLineDash

Set the stroke dash to use.

canvas.setStrokeDash(segments: number[]) => Canvasimo;

getStrokeDashAlias: getLineDash

Get the stroke dash that is being used.

canvas.getStrokeDash() => number[];

setStrokeDashOffsetAlias: setLineDashOffset

Set the stroke dash offset to use.

canvas.setStrokeDashOffset(value: number) => Canvasimo;

getStrokeDashOffsetAlias: getLineDashOffset

Get the stroke dash offset that is being used.

canvas.getStrokeDashOffset() => number;

setStrokeJoinAlias: setLineJoin

Set the stroke join to use.

canvas.setStrokeJoin(value: LineJoin) => Canvasimo;
type LineJoin = 'bevel' | 'round' | 'miter';

getStrokeJoinAlias: getLineJoin

Get the stroke join that is being used.

canvas.getStrokeJoin() => LineJoin;
type LineJoin = 'bevel' | 'round' | 'miter';

setStrokeWidthAlias: setLineWidth

Set the stroke width to use.

canvas.setStrokeWidth(value: number) => Canvasimo;

getStrokeWidthAlias: getLineWidth

Get the stroke width that is being used.

canvas.getStrokeWidth() => number;

setMiterLimit

Set the miter limit to use.

canvas.setMiterLimit(value: number) => Canvasimo;

getMiterLimit

Get the miter limit that is being used.

canvas.getMiterLimit() => number;

Fill styles

A collection of methods for getting and setting fill styles, and applying fills to existing shapes.

fill

Apply a fill to the current shape.

canvas.fill(color?: string) => Canvasimo;
canvas.fill(fillRule?: FillRule) => Canvasimo;
canvas.fill(color: string, fillRule: FillRule) => Canvasimo;
type FillRule = 'nonzero' | 'evenodd';

fillCanvas

Apply a fill to the entire canvas area.

canvas.fillCanvas(color?: string) => Canvasimo;

clearCanvas

Clear the entire canvas area

canvas.clearCanvas() => Canvasimo;

clearRect

Clear a rectangular area of the canvas.

canvas.clearRect(x: number, y: number, width: number, height: number) => Canvasimo;

setFillAlias: setFillStyle

Set the fill to use.

canvas.setFill(value: FillOrStrokeStyle) => Canvasimo;
type FillOrStrokeStyle = string | CanvasGradient | CanvasPattern;

getFillAlias: getFillStyle

Get the fill that is being used.

canvas.getFill() => FillOrStrokeStyle;
type FillOrStrokeStyle = string | CanvasGradient | CanvasPattern;

createLinearGradient

Create a linear gradient to use as a fill.

canvas.createLinearGradient(x0: number, y0: number, x1: number, y1: number) => CanvasGradient;

createRadialGradient

Create a radial gradient to use as a fill.

canvas.createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number) => CanvasGradient;

createPattern

Create a pattern to be used as a fill.

canvas.createPattern(image: HTMLCanvasElement | HTMLImageElement | HTMLVideoElement, repetition: string) => CanvasPattern;

drawImage

Draw an image to the canvas. If the second position / size arguments are supplied, the first will be used for cropping the image, and the second for the position and size it will be drawn.

canvas.drawImage(image: ImageLike, dstX: number, dstY: number) => Canvasimo;
canvas.drawImage(image: ImageLike, dstX: number, dstY: number, dstW: number, dstH: number) => Canvasimo;
canvas.drawImage(image: ImageLike, srcX: number, srcY: number, srcW: number, srcH: number, dstX: number, dstY: number, dstW: number, dstH: number) => Canvasimo;
type ImageLike = HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap;

Image Data

A collection of methods for creating, putting, or getting image data about the canvas.

getDataURL

Get a data URL of the current canvas state.

canvas.getDataURL(type?: string, ...args: any[]) => string;

createImageData

Create image data with either the width and height specified, or with the width and height of a the image data supplied.

canvas.createImageData(width: number, height: number) => ImageData;
canvas.createImageData(ImageData: ImageData) => ImageData;

getImageData

Get the image data from an area of the canvas.

canvas.getImageData(sx: number, sy: number, sw: number, sh: number) => ImageData;

putImageData

Draw image data onto the canvas.

canvas.putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number) => Canvasimo;

getPixelData

Get image data about a specific pixel.

canvas.getPixelData(x: number, y: number) => Uint8ClampedArray;

getPixelColor

Get the color of a specific pixel.

canvas.getPixelColor(x: number, y: number) => string;

Color Helpers

A collection of methods to help with creating color strings.

createHSL

Create an HSL color string from the given values.

canvas.createHSL(h: number, s: number, l: number) => string;

createHSLA

Create an HSLA color string from the given values.

canvas.createHSLA(h: number, s: number, l: number, a: number) => string;

createRGB

Create an RGB color string from the given values.

canvas.createRGB(r: number, g: number, b: number) => string;

createRGBA

Create an RGBA color string from the given values.

canvas.createRGBA(r: number, g: number, b: number, a: number) => string;

getHSLFromHSLA

Return an HSL color string from the given HSLA color string.

canvas.getHSLFromHSLA(color: string) => string;

getRGBFromRGBA

Return an RGB color string from the given RGBA color string.

canvas.getRGBFromRGBA(color: string) => string;

Converting Sizes

A collection of methods to help with calculating and converting sizes, and distances.

getFractionFromPercent

Get a fraction from the provided percent value e.g. 80 returns 0.8.

canvas.getFractionFromPercent(percent: number) => number;

getPercentFromFraction

Get a percent from the provided fraction value e.g. 0.7 returns 70.

canvas.getPercentFromFraction(fraction: number) => number;

getFractionOfWidth

Returns the actual value of a fraction of the canvas width e.g. a canvas with a width of 200 returns 100 if the provided value is 0.5.

canvas.getFractionOfWidth(fraction: number) => number;

getFractionOfHeight

Returns the actual value of a fraction of the canvas height e.g. a canvas with a height of 100 returns 20 if the provided value is 0.2.

canvas.getFractionOfHeight(fraction: number) => number;

getPercentOfWidth

Returns the actual value of a percentage of the canvas width e.g. a canvas with a width of 200 returns 100 if the provided value is 50.

canvas.getPercentOfWidth(percent: number) => number;

getPercentOfHeight

Returns the actual value of a percentage of the canvas height e.g. a canvas with a height of 100 returns 20 if the provided value is 20.

canvas.getPercentOfHeight(percent: number) => number;

getDistance

Returns the distance between 2 points.

canvas.getDistance(x1: number, y1: number, x2: number, y2: number) => number;

Converting Angles

A collection of methods to help with calculating and converting angles.

getRadiansFromDegrees

Get a radian value from the provided degrees e.g. 90 returns 1.5708.

canvas.getRadiansFromDegrees(degrees: number) => number;

getDegreesFromRadians

Get a degree value from the provided radians e.g. 3.14159 returns 180.

canvas.getDegreesFromRadians(radians: number) => number;

getAngle

Get the angle (in radians) between 2 or 3 points.

canvas.getAngle(x1: number, y1: number, x2: number, y2: number) => number;
canvas.getAngle(x1: number, y1: number, x2: number, y2: number, x3: number, y3: number) => number;

Path Plotting

A collection of methods for path drawing.

beginPath

Begin a new path (shape).

canvas.beginPath() => Canvasimo;

closePath

Close the current path (shape).

canvas.closePath() => Canvasimo;

moveTo

Move the starting point of a the next sub-path.

canvas.moveTo(x: number, y: number) => Canvasimo;

lineTo

Connect the last point to the provided coordinates.

canvas.lineTo(x: number, y: number) => Canvasimo;

arcTo

Arc from one point to another.

canvas.arcTo(x1: number, y1: number, x2: number, y2: number, radius: number) => Canvasimo;

bezierCurveTo

Connect the last point to the provided coordinates with a bezier curve (2 control points).

canvas.bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number) => Canvasimo;

quadraticCurveTo

Connect the last point to the provided coordinates with a quadratic curve (1 control point).

canvas.quadraticCurveTo(cpx: number, cpy: number, x: number, y: number) => Canvasimo;

Canvas State

A collection of methods to save, restore, or transform the canvas state.

save

Push the current state of the canvas into a stack that can later be restored.

canvas.save() => Canvasimo;

restore

Restore the most recent state of the canvas that was saved.

canvas.restore() => Canvasimo;

rotate

Add rotation (in radians) to the transform matrix so that shapes can be drawn at an angle.

canvas.rotate(angle: number) => Canvasimo;

scale

Scale the transform matrix so that shapes can be drawn at the provided scale.

canvas.scale(x: number, y: number) => Canvasimo;

translate

Move the canvas origin.

canvas.translate(x: number, y: number) => Canvasimo;

transform

Multiply the current transformation with the provided matrix.

canvas.transform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number) => Canvasimo;

setTransform

Replace the current transformation with the provided matrix.

canvas.setTransform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number) => Canvasimo;

resetTransform

Replace the current transformation with the default matrix: [1, 0, 0, 1, 0, 0].

canvas.resetTransform() => Canvasimo;

clip

Use the current path as a clipping path.

canvas.clip(fillRules?: FillRule) => Canvasimo;
type FillRule = 'nonzero' | 'evenodd';

setOpacityAlias: setGlobalAlpha

Set the opacity to use for drawing.

canvas.setOpacity(value: number) => Canvasimo;

getOpacityAlias: getGlobalAlpha

Get the opacity that is being used.

canvas.getOpacity() => number;

setCompositeOperationAlias: setGlobalCompositeOperation

Set the composite operation to use for drawing.

canvas.setCompositeOperation(value: GlobalCompositeOperation) => Canvasimo;
type GlobalCompositeOperation = 'source-over' | 'source-in' | 'source-out' | 'source-atop' | 'destination-over' | 'destination-in' | 'destination-out' | 'destination-atop' | 'lighter' | 'copy' | 'xor' | 'multiply' | 'screen' | 'overlay' | 'darken' | 'lighten' | 'color-dodge' | 'color-burn' | 'hard-light' | 'soft-light' | 'difference' | 'exclusion' | 'hue' | 'saturation' | 'color' | 'luminosity';

getCompositeOperationAlias: getGlobalCompositeOperation

Get the composite operation that is being used.

canvas.getCompositeOperation() => GlobalCompositeOperation;
type GlobalCompositeOperation = 'source-over' | 'source-in' | 'source-out' | 'source-atop' | 'destination-over' | 'destination-in' | 'destination-out' | 'destination-atop' | 'lighter' | 'copy' | 'xor' | 'multiply' | 'screen' | 'overlay' | 'darken' | 'lighten' | 'color-dodge' | 'color-burn' | 'hard-light' | 'soft-light' | 'difference' | 'exclusion' | 'hue' | 'saturation' | 'color' | 'luminosity';

setImageSmoothingEnabled

Set whether image smoothing should be used.

canvas.setImageSmoothingEnabled(value: boolean) => Canvasimo;

getImageSmoothingEnabled

Get whether image smoothing is being used.

canvas.getImageSmoothingEnabled() => boolean;

setShadowBlur

Set how blurry shadows are.

canvas.setShadowBlur(value: number) => Canvasimo;

getShadowBlur

Get the value of how blurry shadows are.

canvas.getShadowBlur() => number;

setShadowColor

Set the color to be used for shadows.

canvas.setShadowColor(value: string) => Canvasimo;

getShadowColor

Get the color being used for shadows.

canvas.getShadowColor() => string;

setShadowOffsetX

Set how horizontally offset shadows should be.

canvas.setShadowOffsetX(value: number) => Canvasimo;

getShadowOffsetX

Get the value of how horizontally offset shadows should be.

canvas.getShadowOffsetX() => number;

setShadowOffsetY

Set how vertically offset shadows should be.

canvas.setShadowOffsetY(value: number) => Canvasimo;

getShadowOffsetY

Get the value of how vertically offset shadows should be.

canvas.getShadowOffsetY() => number;

Misc

Miscellaneous methods.

tap

Break out of the method chain and execute a callback.

canvas.tap(callback: () => any) => Canvasimo;

repeat

Break out of the method chain and execute a callback with values between start and end, increasing / decreasing by step (start defaults to 0, step defaults to 1). You may return false from the callback at any point to stop at the current iteration.

canvas.repeat(end: number, callback: (i: number) => any) => Canvasimo;
canvas.repeat(start: number, end: number, callback: (i: number) => any) => Canvasimo;
canvas.repeat(start: number, end: number, step: number, callback: (i: number) => any) => Canvasimo;

forEach

Break out of the method chain and loop over the given array, object or string, calling the callback with the value & key / index. You may return false from the callback at any point to stop at the current iteration.

canvas.forEach(str: string, callback: (value: string, index: number) => any) => Canvasimo;
canvas.forEach(obj: any[], callback: (value: any, index: number) => any) => Canvasimo;
canvas.forEach(obj: { [i: string]: any; }, callback: (value: any, key: string) => any) => Canvasimo;

constrain

Constrain a number between a minimum and maximum value.

canvas.constrain(value: number, min: number, max: number) => number;

map

Map a value from one range to another e.g. mapping 0.5 from 0-1 to 0-10 returns 5.

canvas.map(value: number, fromStart: number, fromEnd: number, toStart: number, toEnd: number) => number;

drawFocusIfNeeded

Draw a focus ring around the current path, or the path supplied, if the element supplied has focus.

canvas.drawFocusIfNeeded(element: Element) => Canvasimo;

isPointInPath

Returns whether the given point is within the current or given path.

canvas.isPointInPath(x: number, y: number, fillRule?: FillRule) => boolean;
type FillRule = 'nonzero' | 'evenodd';

isPointInStroke

Returns whether the given point is within the area contained by applying a stroke to the current or given path.

canvas.isPointInStroke() => boolean;

getVersionAlias: version

Return the current version of Canvasimo (and log to console if logInfo parameter is true)

canvas.getVersion(logInfo?: boolean) => string;