DEV Community

Cover image for I Made an NPM Package to Render text on HTML5 Canvas
Geon George
Geon George

Posted on

I Made an NPM Package to Render text on HTML5 Canvas

Rendering text onto HTML5 Canvases has always been a hassle for me.

The Problem

There was no proper way to align text, to wrap words if it overflows and even to properly position text without knowing the contents of the text.

Larger packages had this feature but I didn't wanna import a whole canvas library just to render some text.

Enter Canvas-Txt

I made a library called Canvas-Txt, which will let you render textboxes to html canvases and has all sorts of aligning and multi-line features

I created this for myself and it grew with some community help. This package was released to NPM and has some weekly downloads now.

I added some major changes and just released V2 of this.

Features

  • Multiline text
  • Auto line breaks
  • Horizontal Align
  • Vertical Align
  • Easy Debugging

URLs

Github: https://github.com/geongeorge/canvas-txt

Demo: http://canvas-txt.geongeorge.com/

Discussion (9)

Collapse
bariscc profile image
Baris Can Ceylan

Congrats, nice little package!
One improvement I can think of is making it responsive, perhaps props for different breakpoints.

As a note: Keep in mind that text in canvas (or anything in canvas really) is not accessible. It's always best to use semantic html where you can to provide contextual data & better accessibility.

Collapse
geongeorge profile image
Geon George Author

Thank you!
I used to have a solution where you drop in '\n' to add a custom breakpoint.
This could be added in a future version.

Collapse
sergeylukin profile image
Sergey Lukin

Looks great! How do yo maintain your demo page? Is demo's repo public? I'd love to learn from it.

Collapse
geongeorge profile image
Geon George Author

I made it with vue and buefy.
It was private. I made it public for you ;) . Here you go: github.com/geongeorge/Canvas-txt-d...

Collapse
sergeylukin profile image
Sergey Lukin

You are the man! Thank you

Collapse
adam_cyclones profile image
Adam Crockett

Is this for gl contexts?

Collapse
geongeorge profile image
Geon George Author

I have very little idea about Web Gl, but this should work on any canvas which allows you to draw a line on it.

Collapse
jwp profile image
John Peters • Edited

Was creating npm packages difficult?Any tips?

Collapse
geongeorge profile image
Geon George Author

Not really.
I forgot which one I used but there are many boilerplates.
Or just clone my repo and just change the js file.(for smaller plugins)