BBC's guide to development
  • General

    • About
    • Tools
    • Git(hub)
    • Showpad
    • Hosting
    • Maintenance
    • Security
    • Go live checklist
  • Front-end development

    • Bundlers
    • CSS/SCSS
    • Javascript
    • Vue
    • PHP
    • Mails
    • Dev Faq
  • Functions
  • Mixins
  • General

    • OOP Structure
  • Component Classes

    • Accordion
    • App
    • Component
    • HighwayApp
    • Popup
    • PNG Sequencer
    • Tab
  • Manager Classes

    • BountListenerMgr
    • Cache
    • Configuration
    • InViewStateMgr
    • Instance Manager
    • Event dispatcher
  • Factories

    • SwiperFactory
  • PDF

    • AssetLoader
    • BasePdfDoc
    • TemplatePdfDoc
    • CustomPdfDoc
  • Utility functions

    • canvas
    • Connection Status
    • css
    • dev
    • placeholder
    • dom
    • fetch
    • json
    • object
    • scroll
    • scrollbar
    • spreadsheets
    • string
    • url
  • General

    • ComponentMgr
    • ThreeJsViewer
  • Components

    • ComponentMgr
    • GltfModel
    • Snappable
    • Socket
    • ThreeJsViewer
    • ThreeJsViewerCamera
  • Loaders

    • ConfigurationSerializer
    • GltfBlockParser
  • Utils

    • CanvasInputAdapter
    • CollisionManager
    • SocketGridExpander
    • blender
    • headless
  • General

    • Troubleshooting
    • Legacy
  • Components

    • AssetBar
    • ConfigGenerator
    • ShowpadApp
  • Managers

    • Assets
    • AppsDb
    • Config
  • Utils

    • Connection Status
    • general
    • showpad-interactive
    • showpad-upload
  • Components

    • Accordion
    • BackButton
    • Breadcrumb
    • ByltButton
    • Hamburger
    • Icon
    • Logo
    • Loader
    • Modal
    • Popup
    • Prompt
    • ProgressBar
    • TextLoader
  • Composables

    • useDebugMode
    • useConnectionStatus
  • Utils

    • dom
    • props
  • General

    • General
    • Tracking
  • Components

    • Accordion
    • ActionButton
    • AssetItem
    • AssetList
    • BackButton
    • ConfigGenButton
    • Logo
    • Media
    • Modal
    • Popup
    • Prompt
    • SPButton
    • SPRouterView
    • SPTrackedRouterLink
    • TextLoader
    • View
  • Composables

    • useConnectionStatus
  • Stores

    • useAppsDbStore
    • useBreadcrumbStore
    • useShowpadAPIStore
    • useShowpadSDKStore
    • useSpConfigStore
    • useSpStore
    • useSpTrackingStore
  • The New Kit

    • General
    • Installation & Usage
    • ACF Blocks
    • PHPCS
    • Functions
    • Vite
    • WP Config
    • Staging Deployment
  • Best Practices

    • Page Structure
    • Fonts/Typography
  • Todo
GitHub
  • General

    • About
    • Tools
    • Git(hub)
    • Showpad
    • Hosting
    • Maintenance
    • Security
    • Go live checklist
  • Front-end development

    • Bundlers
    • CSS/SCSS
    • Javascript
    • Vue
    • PHP
    • Mails
    • Dev Faq
  • Functions
  • Mixins
  • General

    • OOP Structure
  • Component Classes

    • Accordion
    • App
    • Component
    • HighwayApp
    • Popup
    • PNG Sequencer
    • Tab
  • Manager Classes

    • BountListenerMgr
    • Cache
    • Configuration
    • InViewStateMgr
    • Instance Manager
    • Event dispatcher
  • Factories

    • SwiperFactory
  • PDF

    • AssetLoader
    • BasePdfDoc
    • TemplatePdfDoc
    • CustomPdfDoc
  • Utility functions

    • canvas
    • Connection Status
    • css
    • dev
    • placeholder
    • dom
    • fetch
    • json
    • object
    • scroll
    • scrollbar
    • spreadsheets
    • string
    • url
  • General

    • ComponentMgr
    • ThreeJsViewer
  • Components

    • ComponentMgr
    • GltfModel
    • Snappable
    • Socket
    • ThreeJsViewer
    • ThreeJsViewerCamera
  • Loaders

    • ConfigurationSerializer
    • GltfBlockParser
  • Utils

    • CanvasInputAdapter
    • CollisionManager
    • SocketGridExpander
    • blender
    • headless
  • General

    • Troubleshooting
    • Legacy
  • Components

    • AssetBar
    • ConfigGenerator
    • ShowpadApp
  • Managers

    • Assets
    • AppsDb
    • Config
  • Utils

    • Connection Status
    • general
    • showpad-interactive
    • showpad-upload
  • Components

    • Accordion
    • BackButton
    • Breadcrumb
    • ByltButton
    • Hamburger
    • Icon
    • Logo
    • Loader
    • Modal
    • Popup
    • Prompt
    • ProgressBar
    • TextLoader
  • Composables

    • useDebugMode
    • useConnectionStatus
  • Utils

    • dom
    • props
  • General

    • General
    • Tracking
  • Components

    • Accordion
    • ActionButton
    • AssetItem
    • AssetList
    • BackButton
    • ConfigGenButton
    • Logo
    • Media
    • Modal
    • Popup
    • Prompt
    • SPButton
    • SPRouterView
    • SPTrackedRouterLink
    • TextLoader
    • View
  • Composables

    • useConnectionStatus
  • Stores

    • useAppsDbStore
    • useBreadcrumbStore
    • useShowpadAPIStore
    • useShowpadSDKStore
    • useSpConfigStore
    • useSpStore
    • useSpTrackingStore
  • The New Kit

    • General
    • Installation & Usage
    • ACF Blocks
    • PHPCS
    • Functions
    • Vite
    • WP Config
    • Staging Deployment
  • Best Practices

    • Page Structure
    • Fonts/Typography
  • Todo
GitHub
  • Canvas Utilities

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 transparent HTMLCanvasElement
  • '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
  }
});
Edit this page
Last Updated: 4/27/26, 12:56 PM
Contributors: Nicolas Jaenen