I recommend using 2.0.0 branch and the 2.0.0-alpha
releases. 1.x will not be developed further.
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:
- Convert HTML text into tokens.
- Arrange tokens into arranged text.
- Render the arranged text.
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