DEV Community

Cover image for Multiline Text in HTML Canvas
Geon George
Geon George

Posted on

Multiline Text in HTML Canvas

I've recently given a facelift to Canvas-Txt, a project that I initially launched some moons ago. For those not in the know, Canvas-Txt is a teensy-weensy library that does one job, and one job only - render multiline text on your HTML5 Canvas, without hanging on the coattails of any dependencies.

Now, let me show you

https://github.com/geongeorge/Canvas-Txt

Demo

To give you an idea, let me walk you through a simple use-case scenario:

First, install Canvas Txt either via yarn or npm:

yarn add canvas-txt

or

npm i canvas-txt
Enter fullscreen mode Exit fullscreen mode
<canvas id="myCanvas" width="500" height="500"></canvas>
Enter fullscreen mode Exit fullscreen mode
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

And there you have it. Your multiline text, neatly rendered on an HTML canvas.

What's even cooler is that you can do this in Node too! Just have a look at the Node js demo here https://github.com/geongeorge/Canvas-Txt/blob/master/src/node-test.ts

Summing Up

That's pretty much it. With Canvas Txt v4, I've aimed to simplify your journey of handling multiline text in HTML canvas.

Whether you're just dabbling in canvas or are an experienced pro, I hope you'll find Canvas Txt useful.

As always, if you have any suggestions, comments, or just want to give a shout out, hit me up on my Twitter!

Top comments (0)