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!

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay