A way to render rich text in Canvas without resorting to SVG's <foreignObject>
. It supports a very limited subset of HTML and CSS.
This library was written in TypeScript but will also work in projects written in JavaScript.
Add it to your project via:
npm i --save canvas-rich-text
You can find an interactive demo here.
The full documentation can be found here.
The library can be used like this:
import {arrangeText, renderArrangedText, HtmlTokenizer} from 'canvas-rich-text';
const text = `<p>Paragraph <strong>bold</strong> <em>italic</em></p>`;
const tokens = HtmlTokenizer.tokenizeString(text);
const arrangedText = arrangeText(tokens, {
wordWrapWidth: 300,
spaceWidth: 8,
lineSpacing: 5
});
renderArrangedText(arrangedText, canvas, 0, 0);
The library works in three steps:
You can write your own parser to create the tokens from any format you want, or create the tokens directly.
This project is licensed under the MIT License - see the LICENSE.md file for details
Generated using TypeDoc