But let’s say that what you really wanted was an effective “This is some text”, that is something like:
That’s a nice target, and would extend the capability of the canvas element considerably. But imagine getting inside the browser canvas code to make such a change isn’t possible. What to do?
The way to get around this is just drawing piecewise on the canvas:
that is, break the multi-font string into single-font regions, and paint each in turn, offsetting the cursor forward to draw the next text in the right place.
Making a function to draw arbitrary strings of html on a canvas now becomes the goal. It needs to do what was done above:
The complexity has been pushed down into the
Unfortunately, that function isn’t available out of the box.
Schematically, to handle our simple bold text above, it looks like:
This is a very simplified outline, but illustrates the idea. A full implementation would need to
- verify the html
- handle all font modifiers (not just bold)
- properly emit the blocks
- handle margins and multi-line text
- maintain font modifiers across lines
and more. The point is that it’s not really hard to translate multi-font text into a series of single-font blocks, some code just needs to be written to do it.
I’ve recently added such code to the vis.js, an open source visualization library for browsers, extending its label text features to include multi-font rendering. The functionality should be released in the 7.18 version of the package.