Skip to content

How to use multiple colors in one text #110

Answered by samizdatco
Farman52 asked this question in Q&A
Discussion options

You must be logged in to vote

It's not possible in a single step. You need to use a combination of fillText and measureText to lay out the line yourself and change the fillStyle in between.

Something like this will work:

let prefix = "correct horse ",
    highlighted = "battery",
    suffix = " staple"

let x = 100,
    y = 100

ctx.font = '20px Helvetica'
ctx.fillText(prefix, x, y)
x += ctx.measureText(prefix).width

ctx.fillStyle = 'red'
ctx.fillText(highlighted, x, y)
x += ctx.measureText(highlighted).width

ctx.fillStyle = 'black'
ctx.fillText(suffix, x, y)

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@Farman52
Comment options

Answer selected by Farman52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants