Skip to content

Instantly share code, notes, and snippets.

@mrcoles
Last active Aug 19, 2022
Embed
What would you like to do?
A simple function for writing mixed color and/or font text on an HTML5 Canvas object.
// # HTML5 Canvas: Fill Mixed Text
//
// ctx: CanvasRenderingContext2D
// args: array of objects of form
// { text: string, fillStyle?: string, font?: string }
// x: number
// y: number
//
const fillMixedText = (ctx, args, x, y) => {
let defaultFillStyle = ctx.fillStyle;
let defaultFont = ctx.font;
ctx.save();
args.forEach(({ text, fillStyle, font }) => {
ctx.fillStyle = fillStyle || defaultFillStyle;
ctx.font = font || defaultFont;
ctx.fillText(text, x, y);
x += ctx.measureText(text).width;
});
ctx.restore();
};
export default fillMultiColorText;
@mrcoles
Copy link
Author

mrcoles commented Sep 4, 2018

This defaults to using whatever ctx.font and ctx.fillStyle are set to before the call is made, however in any of the args, you can override either of these values, e.g.,

const ctx = canvas.getContext('2d');
ctx.fillStyle = '#000';
ctx.font = '20px Helvetica';

const args = [
  { text: 'I’m sorry, ' },
  { text: 'Dave. ', fillStyle: 'red' },
  { text: 'I’m ' },
  { text: 'afraid ', font: 'italic 20px Helvetica' },
  { text: 'I can’t do that.' }
];

fillMixedText(ctx, args, 10, 40);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment