Skip to content

Instantly share code, notes, and snippets.

@mrcoles
Last active February 14, 2023 13:15
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrcoles/0dfaab93a1c899e5f46690676c8c29e5 to your computer and use it in GitHub Desktop.
Save mrcoles/0dfaab93a1c899e5f46690676c8c29e5 to your computer and use it in GitHub Desktop.
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