Skip to main content

@rtorcato/browser-common / canvas

canvas

Functions

createCanvas()

createCanvas(width, height): HTMLCanvasElement

Defined in: canvas/index.ts:13

Creates a canvas element with the given width and height.

Parameters

width

number

The width of the canvas.

height

number

The height of the canvas.

Returns

HTMLCanvasElement

The created HTMLCanvasElement.

Example

import { createCanvas } from '@rtorcato/browser-common/canvas'
const canvas = createCanvas(640, 480)
document.body.append(canvas)

getCanvasContext2D()

getCanvasContext2D(canvas): CanvasRenderingContext2D | null

Defined in: canvas/index.ts:31

Gets the 2D rendering context from a canvas element.

Parameters

canvas

HTMLCanvasElement

The canvas element.

Returns

CanvasRenderingContext2D | null

The 2D rendering context, or null if not available.

Example

import { createCanvas, getCanvasContext2D } from '@rtorcato/browser-common/canvas'
const ctx = getCanvasContext2D(createCanvas(100, 100))
ctx?.fillRect(0, 0, 50, 50)

clearCanvas()

clearCanvas(canvas): void

Defined in: canvas/index.ts:44

Clears the entire canvas.

Parameters

canvas

HTMLCanvasElement

The canvas element to clear.

Returns

void

Example

import { clearCanvas } from '@rtorcato/browser-common/canvas'
clearCanvas(myCanvas)

drawImageOnCanvas()

drawImageOnCanvas(canvas, image, dx, dy): void

Defined in: canvas/index.ts:63

Draws an image onto a canvas.

Parameters

canvas

HTMLCanvasElement

The canvas element.

image

CanvasImageSource

The image to draw (HTMLImageElement, HTMLCanvasElement, etc.).

dx

number

The x coordinate.

dy

number

The y coordinate.

Returns

void

Example

import { drawImageOnCanvas } from '@rtorcato/browser-common/canvas'
drawImageOnCanvas(myCanvas, image, 10, 20)

canvasToDataURL()

canvasToDataURL(canvas, type?, quality?): string

Defined in: canvas/index.ts:88

Converts the canvas content to a data URL (base64 image string).

Parameters

canvas

HTMLCanvasElement

The canvas element.

type?

string = 'image/png'

The image MIME type (default: 'image/png').

quality?

number

The image quality for image/jpeg or image/webp (0 to 1).

Returns

string

The data URL string.

Example

import { canvasToDataURL } from '@rtorcato/browser-common/canvas'
const png = canvasToDataURL(myCanvas)
const jpg = canvasToDataURL(myCanvas, 'image/jpeg', 0.8)

fillCanvas()

fillCanvas(canvas, color): void

Defined in: canvas/index.ts:106

Fills the entire canvas with a given color.

Parameters

canvas

HTMLCanvasElement

The canvas element.

color

string

The fill color (CSS color string).

Returns

void

Example

import { fillCanvas } from '@rtorcato/browser-common/canvas'
fillCanvas(myCanvas, '#fafafa')