Canvas-Txt: Multiline Text Magic on HTML5 Canvas

Geon George - Nov 3 '23 - - Dev Community

As developers, we've often been in situations where we need to render text on a canvas element in HTML5. It could be for a game, a custom chart, or even an advanced animation. But, anyone who's tried this knows that the native canvas API is... a bit limited when it comes to handling text. Enter Canvas-Txt 📐✨, a minuscule, dependency-free library that transforms how we draw text on HTML5 canvas.

What's Canvas-txt?

Canvas-Txt extends the native canvas text rendering capabilities with a set of much-needed features:

  • Multiline Text: Easily render paragraphs.
  • Auto Line Breaks: No more manual calculation for breaking lines.
  • Text Alignment: Supports horizontal, vertical, and even justify alignment.
  • Debugging Tools: Comes with visual aids to help place your text exactly where you want it.
  • Performance: It's built for speed, so no more trade-offs between functionality and performance.

Image description

See It in Action

Before we dive into the code, take a peek at the live demo here to see what you'll be capable of after this tutorial.

Setting Up

First things first, let's add Canvas-Txt to your project:

yarn add canvas-txt

# Or with npm
npm i canvas-txt
Enter fullscreen mode Exit fullscreen mode

The Basics: Drawing Text

Here's the simplest example to get you started. Add a canvas element to your HTML:

<canvas id="myCanvas" width="500" height="500"></canvas>
Enter fullscreen mode Exit fullscreen mode

Now, let's draw some text on it using Canvas-Txt:

import { drawText } from 'canvas-txt'

const c = document.getElementById('myCanvas')
const ctx = c.getContext('2d')

ctx.clearRect(0, 0, 500, 500)

const txt = 'Lorem ipsum dolor sit amet'

const { height } = drawText(ctx, txt, {
  x: 100,
  y: 200,
  width: 200,
  height: 200,
  fontSize: 24,
})

console.log(`Total height = ${height}`)
Enter fullscreen mode Exit fullscreen mode

When you run this code, you’ll see "Lorem ipsum dolor sit amet" beautifully rendered on the canvas, enclosed in a 200x200px box starting from position (100,200).

Using Canvas-Txt on the Server with Node.js

If you're working in a Node.js environment, you can use Canvas-Txt with node-canvas:

const { createCanvas } = require('canvas')
const { drawText } = require('canvas-txt')
const fs = require('fs')

function main() {
  const canvas = createCanvas(400, 400)
  const ctx = canvas.getContext('2d')
  const txt = 'Hello World!'

  const { height } = drawText(ctx, txt, {
    x: 100,
    y: 200,
    width: 200,
    height: 200,
    fontSize: 24,
  })

  const buffer = canvas.toBuffer('image/png')
  fs.writeFileSync('output.png', buffer)
  console.log(`Total height = ${height}`)
}

main()
Enter fullscreen mode Exit fullscreen mode

With this setup, you can generate images on the server side that include dynamic text content.

Conclusion

And there you have it! Canvas-Txt is a powerful and easy-to-use solution for all your canvas text rendering needs. Whether you’re working on a dynamic web application or generating images on the server side, Canvas-Txt simplifies the process, giving you the ability to focus on creating a great user experience rather than wrestling with text metrics.

To dive even deeper and to learn more about the customization options available, be sure to check out the official Canvas-Txt documentation. With this tool in your development arsenal, you're well-equipped to make your canvas text renderings as simple or sophisticated as your project requires.

Happy coding, and may your text always align perfectly on your canvas!

. . . . . . . . .