Last active
February 14, 2023 13:15
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// # 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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This defaults to using whatever
ctx.font
andctx.fillStyle
are set to before the call is made, however in any of theargs
, you can override either of these values, e.g.,