Class CanvasHelper

A wrapper for the CANVAS element that scales the canvas for high-DPI displays and helps with resizing.

const canvas = new CanvasHelper(`#my-canvas`, { fill: `viewport` });
const { ctx, width, height } = canvas.ctx; // Get drawing context, width & height

Draw whenever it is resized using the 'resize' event

canvas.addEventListener(`resize`, ({ctx, size}) => {
// Use ctx...
});

Or provide a function when initialising:

const onResize = (ctx, size) => {
// Do drawing
}
const canvas = new CanvasHelper(`#my-canvas`, { fill: `viewport`, onResize });

Automatically draw at animation speeds:

const draw = () => {
}
const canvas = new CanvasHelper(`#my-canvas`, { fill: `viewport`, draw });

Hierarchy (view full)

Constructors

Properties

el: HTMLCanvasElement

Accessors

  • get center(): {
        x: number;
        y: number;
    }
  • Gets the center coordinate of the canvas

    Returns {
        x: number;
        y: number;
    }

    • x: number
    • y: number
  • get ctx(): CanvasRenderingContext2D
  • Gets the drawing context

    Returns CanvasRenderingContext2D

  • get dimensionMax(): number
  • Returns the width or height, whichever is largest

    Returns number

  • get dimensionMin(): number
  • Returns the width or height, whichever is smallest

    Returns number

  • get height(): number
  • Gets the logical height of the canvas See also: width, size

    Returns number

  • get isDisposed(): boolean
  • Returns boolean

  • get ratio(): number
  • Gets the current scaling ratio being used to compensate for high-DPI display

    Returns number

  • get toAbsolute(): Scaler
  • Returns a Scaler that converts from relative to absolute coordinates. This is based on the canvas size.

    // Assuming a canvas of 800x600
    toAbsolute({ x: 1, y: 1 }); // { x: 800, y: 600}
    toAbsolute({ x: 0, y: 0 }); // { x: 0, y: 0}
    toAbsolute({ x: 0.5, y: 0.5 }); // { x: 400, y: 300}

    Returns Scaler

  • get toRelative(): Scaler
  • Returns a Scaler that converts from absolute to relative coordinates. This is based on the canvas size.

    // Assuming a canvas of 800x500
    toRelative({ x: 800, y:600 }); // { x: 1, y: 1 }
    toRelative({ x: 0, y: 0 }); // { x: 0, y: 0 }
    toRelative({ x: 400, y: 300 }); // { x: 0.5, y: 0.5 }

    Returns Scaler

  • get width(): number
  • Gets the logical width of the canvas See also: height, size

    Returns number

Methods

  • Clears the canvas.

    Shortcut for: this.ctx.clearRect( 0, 0, this.width, this.height)

    Returns void

  • Parameters

    • strokeStyle: string = ...

    Returns void

  • Parameters

    • Optionalcolour: string

    Returns void

  • Parameters

    Returns void