If you’ve had a chance to use an html canvas to render graphics in a web app, you found you were limited to using a single
font to draw text on the screen in JavaScript:
ctx.setFont("16px Helvetica")ctx.drawText(x,y,"This is some text")
But let’s say that what you really wanted was an effective “This is some text”, that is something like:
ctx.drawText(x,y,"<b>This</b> is some text")
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:
ctx.setFont("bold 16px Helvetica")ctx.drawText(x,y,"This")letoffset=ctx.measureText("This").widthctx.setFont("16px Helvetica")ctx.drawText(x+offset,y," is some text")
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 splitHtml function. Unfortunately, that function isn’t available out of the box.
Creating the function to split html text into a series of blocks is an exercise in parsing, a well-studied part of Computer Science going back over half a century. There are a few general purpose parsing packages for javascript, but it’s a pretty straightforward piece of code to write by hand. Schematically, it’ll look like:
splitHtml = (text) => {
iterating across text,
if <b> is found
emit block
else if </b> is found
emit block
else
grow text
emit block
}
This is very simplified view.
No verification of the html is being done
Nothing more than bold is being handled
No text resets are shown
No memory of the font mod is maintained
Nothing on block emission is detailed
etc.
A working implementation needs to do all of this and more. The point is that it’s not really hard to translate marked-up text into blocks, it’s just tedious.
So, it isn’t hard to do multi-font html canvas rendering, 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 rendering features to include multi-font. The functionality will be in the 7.18 release of the package, but until then it is currently available on their develop branch.
Callibrity is a software consultancy specializing in solving complex challenges while upskilling teams, ensuring long-term success beyond project delivery. Built around a team of elite technologists, our process is simple: deliver precision, efficiency, and measurable value – in weeks, not months. Trusted by leaders in Fortune 500 companies, and many enterprise, and mid-market clients, who choose Callibrity for modernizing legacy systems, platform engineering, digital product development, evaluating emerging technology, and more.