04 September 2018

How to draw multi-colored text on an HTML5 canvas

The HTML5 canvas fillText method is very barebones. If you’re looking to write multi-colored or mixed font style text (even just bold or italicize a word), you’ll quickly realize that you need to make independent calls to fillText for each change in the text style.

Fortunately, this can be pulled off by taking advantage of the ctx.measureText(text) method, which you can use to track where the last part of text finished off.

I wrote a simple convenience function fillMixedText to showcase how to do this and posted it in this gist:


Did you find this helpful or fun? Please donate!

donate via btc or eth

btc: 18jCzwsZDGQYcs6Kyv92pd4683cnnxm1Dd
eth: 0xC285F21Cb271Cb4B3F70c4C47B2f7B26063AF590
paypal: paypal.me/mrcoles
comments powered by Disqus

Peter Coles

Peter Coles

is a software engineer who lives in NYC, works at Ringly, and blogs here.
More about Peter »

github · soundcloud · @lethys · rss

It’s time to get big money out of politics. Join the kick-started campaign to put government back in the hands of the people. Pledge mayday.us now