Canvas Utilities
import { ctxWrapText, trimCanvas } from '@bbc/front-end-kit/js/utils/canvas';
This file contains utility functions for working with the HTML Canvas API, including text wrapping and trimming transparent edges from canvases.
ctxWrapText
Wraps text within a specified width by breaking it into multiple lines and drawing each line on the canvas.
Parameters
context(CanvasRenderingContext2D | HTMLCanvasElement): The canvas 2D rendering context or canvas element.text(string): The text to wrap.x(number): X coordinate where to start drawing the text.y(number): Y coordinate where to start drawing the text.maxWidth(number): Maximum width in pixels for each line of text.lineHeight(number): Height in pixels between each line of text.
Returns
An object containing:
width(number): Width in pixels of the widest line.height(number): Total height in pixels of all lines.lines(Array<{ text: string, metrics: TextMetrics }>): Array of objects for each line, with the text and its metrics.
Example
import { ctxWrapText } from '@bbc/front-end-kit/js/utils/canvas';
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
ctx.font = '16px Arial';
const result = ctxWrapText(ctx, 'This is a long string that should wrap to multiple lines.', 10, 30, 200, 24);
console.log(result.width, result.height, result.lines);
trimCanvas
Trims transparent pixels from the edges of a canvas and returns the trimmed result in the desired format.
Parameters
sourceCanvas(HTMLCanvasElement): The canvas to trim.options(object, optional): Optional parameters.outputType(string, default'canvas'): Desired output:'canvas','dataURL', or'blob'.mimeType(string, default'image/png'): MIME type for'dataURL'or'blob'.quality(number, optional): Quality for'image/jpeg'or'image/webp'(0 to 1).
Returns
'canvas'→HTMLCanvasElement(trimmed)'dataURL'→string'blob'→Promise<Blob | null>
On a tainted canvas (cross-origin read blocked) or fully transparent canvas, returns a fallback per output type:
'canvas'→ a 1×1 transparentHTMLCanvasElement'dataURL'→ a data URL of a 1×1 transparent canvas'blob'→Promise.resolve(null)
Example
import { trimCanvas } from '@bbc/front-end-kit/js/utils/canvas';
const canvas = document.createElement('canvas');
// ... draw something on the canvas ...
// Trim and get a new canvas
const trimmed = trimCanvas(canvas);
document.body.appendChild(trimmed);
// Trim and get a data URL
const dataUrl = trimCanvas(canvas, { outputType: 'dataURL' });
console.log(dataUrl);
// Trim and get a Blob
trimCanvas(canvas, { outputType: 'blob', mimeType: 'image/png' }).then(blob => {
if (blob) {
// do something with the blob
}
});