Render Formatted Text on Canvas with Canvas Text Paragraphs

Category: Javascript , Text | July 9, 2024
Views Total:15 views
Official Page:Go to website
Last Update:July 9, 2024


Render Formatted Text on Canvas with Canvas Text Paragraphs


Canvas Text Paragraphs is a JavaScript library for rendering formatted text on HTML5 canvas elements. It provides several formatting options to control how your text is rendered on the Canvas, including width and height, alignment, indentation, spacing, vertical positioning, and more.

This library enables developers to control text rendering on Canvas precisely. You can create more complex text layouts to improve the visual appeal and readability of canvas-based applications. It can be useful for projects requiring custom text formatting not easily achieved with standard HTML and CSS.

How to use it:

1. Install the Canvas Text Paragraphs library with npm:

npm install @sch39/canvas-text-paragraphs

2. Import it into your project:

import canvasTextParagraphs from '@sch39/canvas-text-paragraphs'
// OR
<script src="index.umd.js"></script>

3. Create a canvas element in your HTML:

<canvas width="400" height="600" id="myCanvas"></canvas>

4. Define the text string you want to render:

const text = `Paragraph 1
Paragraph 2`

5. Set formatting options:

  • height=’auto’ – The height of the text area. Can be a number or ‘auto’.
  • width=’auto’ – The width of the text area. Can be a number or ‘auto’.
  • baseLine=’top’ – The baseline alignment of the text. Valid values are ‘top’, ‘hanging’, ‘middle’, ‘alphabetic’, ‘ideographic’, ‘bottom’.
  • xStart=0 – The x-coordinate where the text starts.
  • yStart=0 – The y-coordinate where the text starts.
  • align=’left’ – The horizontal alignment of the text. Valid values are ‘left’, ‘center’, ‘right’, ‘justify’.
  • verticalAlign=’top’ – The vertical alignment of the text. Valid values are ‘top’, ‘middle’, ‘bottom’.
  • spaceBeforeParagraph=0 – The space before each paragraph in pixels.
  • spaceAfterParagraph=0 – The space after each paragraph in pixels.
  • lineSpacing=’auto’ – The spacing between lines of text. Can be a number or ‘auto’.
  • indent.type=’none’ – The type of indentation. Valid values are ‘none’, ‘firstLine’, ‘hanging’.
  • – The number of spaces to indent.
const options = {
  width: 'auto',
  height: 'auto',
  xStart: 20,
  yStart: 0,
  lineSpacing: 'auto',
  baseLine: 'top',
  align: 'center',
  spaceBeforeParagraph: 2,
  spaceAfterParagraph: 0,
  verticalAlign: 'top',
  indent: {
    type: 'none',
    by: 40

6. Draw each line of text onto the canvas and apply the specified formatting options.

const canvas = document.getElementById("myCanvas")
const ctx = canvas.getContext('2d');
ctx.font = '16px Inter';
ctx.clearRect(0, 0, canvas.width, canvas.height);
canvasTextParagraphs(text, ctx, options);

You Might Be Interested In:

Leave a Reply